Example usage for javax.mail Message setFrom

List of usage examples for javax.mail Message setFrom

Introduction

In this page you can find the example usage for javax.mail Message setFrom.

Prototype

public abstract void setFrom(Address address) throws MessagingException;

Source Link

Document

Set the "From" attribute in this Message.

Usage

From source file:com.mycompany.craftdemo.utility.java

public static void send(long phno, double price, double profit, String domain, String company) {
    HashMap<String, String> domainMap = new HashMap<>();
    domainMap.put("TMobile", "tmomail.net ");
    domainMap.put("ATT", "txt.att.net");
    domainMap.put("Sprint", "messaging.sprintpcs.com");
    domainMap.put("Verizon", "vtext.com");
    String to = phno + "@" + domainMap.get(domain); //change accordingly

    // Sender's email ID needs to be mentioned
    String from = "uni5prince@gmail.com"; //change accordingly
    final String username = "uni5prince"; //change accordingly
    final String password = "savageph8893"; //change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from  w w w. j  a v  a  2s.  c  o  m
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Prices have gone up!!");

        // Now set the actual message
        message.setText("Hello Jane, Stock prices for " + company + " has reached to $" + price
                + " with profit of $" + profit);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.roller.planet.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*from  w  w  w.  j  a va2s . c  om*/
 * 
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.sun.socialsite.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from   ww  w  . j a v  a 2 s. c  o m
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Startup.getMailProvider().getTransport().sendMessage(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Common part for sending message process :
 * <ul>/*from  w  w w  . j  av  a 2  s .com*/
 * <li>initializes a mail session with the SMTP server</li>
 * <li>activates debugging</li>
 * <li>instantiates and initializes a mime message</li>
 * <li>sets the sent date, the from field, the subject field</li>
 * <li>sets the recipients</li>
 * </ul>
 *
 *
 * @return the message object initialized with the common settings
 * @param strRecipientsTo The list of the main recipients email.Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param session The SMTP session object
 * @throws AddressException If invalid address
 * @throws MessagingException If a messaging error occurred
 */
protected static Message prepareMessage(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc,
        String strSenderName, String strSenderEmail, String strSubject, Session session)
        throws MessagingException, AddressException {
    // Instantiate and initialize a mime message
    Message msg = new MimeMessage(session);
    msg.setSentDate(new Date());

    try {
        msg.setFrom(new InternetAddress(strSenderEmail, strSenderName,
                AppPropertiesService.getProperty(PROPERTY_CHARSET)));
        msg.setSubject(MimeUtility.encodeText(strSubject, AppPropertiesService.getProperty(PROPERTY_CHARSET),
                ENCODING));
    } catch (UnsupportedEncodingException e) {
        throw new AppException(e.toString());
    }

    // Instantiation of the list of address
    if (strRecipientsTo != null) {
        msg.setRecipients(Message.RecipientType.TO, getAllAdressOfRecipients(strRecipientsTo));
    }

    if (strRecipientsCc != null) {
        msg.setRecipients(Message.RecipientType.CC, getAllAdressOfRecipients(strRecipientsCc));
    }

    if (strRecipientsBcc != null) {
        msg.setRecipients(Message.RecipientType.BCC, getAllAdressOfRecipients(strRecipientsBcc));
    }

    return msg;
}

From source file:org.apache.roller.weblogger.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//  ww w . jav a  2  s  .  co m
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(String from, String[] to, String[] cc, String[] bcc, String subject,
        String content, String mimeType) throws MessagingException {

    MailProvider mailProvider = WebloggerStartup.getMailProvider();
    if (mailProvider == null) {
        return;
    }

    Session session = mailProvider.getSession();
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (log.isDebugEnabled())
            log.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (log.isDebugEnabled())
                log.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (log.isDebugEnabled())
                log.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (log.isDebugEnabled())
                log.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    Transport transport = mailProvider.getTransport();

    // Try to send while there remain some potentially good addresses
    try {
        do {
            // Avoid a loop if we are stuck
            nAddresses = remainingAddresses.length;

            try {
                // Send to the list of remaining addresses, ignoring the addresses attached to the message
                transport.sendMessage(message, remainingAddresses);
            } catch (SendFailedException ex) {
                bFailedToSome = true;
                sendex.setNextException(ex);

                // Extract the remaining potentially good addresses
                remainingAddresses = ex.getValidUnsentAddresses();
            }
        } while (remainingAddresses != null && remainingAddresses.length > 0
                && remainingAddresses.length != nAddresses);

    } finally {
        transport.close();
    }

    if (bFailedToSome)
        throw sendex;
}

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override/*from  w w w . ja  va 2s .  c  om*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}

From source file:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaVerificacionEmailImp.java

@Override
public void enviarAlerta(List<AlertaVerificacion> alertas) {
    try {/*from  w  w  w.  j  a va 2 s. co m*/
        for (AlertaVerificacion x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta de Verificacin");
            ST contenido = new ST(contenidoRaw);
            contenido.add("placas", x.getPlacas());
            contenido.add("periodo", x.getPeriodo());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaEmailImp.java

@Override
public void enviarAlerta(List<AlertaServicio> alertas) {
    try {/*ww  w  .  jav  a  2 s.c o  m*/
        for (AlertaServicio x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta");
            ST contenido = new ST(contenidoRaw);
            contenido.add("cliente", x.getNombreCliente());
            contenido.add("tipo", x.getTipoAuto());
            contenido.add("marca", x.getMarcaAuto());
            contenido.add("placas", x.getPlacasAuto());
            contenido.add("kilometraje", x.getKilometrajeAuto());
            contenido.add("servicio", x.getDescripcionServicio());
            contenido.add("kilometrajeServicio", x.getKilometrajeServicio());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.xebia.cocktail.MailService.java

public void sendCocktail(Cocktail cocktail, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[Cocktail] " + cocktail.getName());
    String message = cocktail.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(cocktail.getInstructions()) + "\n" //
            + "\n" //
            + cocktailPageUrl;// w ww .j a v  a  2  s  .  c  o  m
    msg.setContent(message, "text/plain");

    Transport.send(msg);
    auditLogger.info("Sent to {} cocktail '{}'", recipient, cocktail.getName());
    sentEmailCounter.incrementAndGet();
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

private void sendResponseMail(final Address sender, final String answer, final String subject)
        throws Exception {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("overseer@thenewoverseer.appspotmail.com", "Overseer"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sender.toString()));
    mimeMessage.setSubject("Re: " + subject);
    mimeMessage.setText(answer);/*from w w w .  j  a v a 2 s  . co  m*/
    Transport.send(mimeMessage);
}