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:rapture.mail.Mailer.java

public static void email(CallingContext context, String templateName,
        Map<String, ? extends Object> templateValues) {
    final SMTPConfig config = getSMTPConfig();
    Session session = getSession(config);
    EmailTemplate template = getEmailTemplate(context, templateName);
    try {/*  w w w.  ja  v  a 2s .  co m*/
        // Instantiate a new MimeMessage and fill it with the required information.
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(config.getFrom()));
        String to = renderTemplate(template.getEmailTo(), templateValues);
        if (StringUtils.isBlank(to)) {
            throw RaptureExceptionFactory.create("No emailTo field");
        }
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(renderTemplate(template.getSubject(), templateValues));
        msg.setSentDate(new Date());
        msg.setContent(renderTemplate(template.getMsgBody(), templateValues), "text/html; charset=utf-8");
        // Hand the message to the default transport service for delivery.
        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Failed to send email", e);
    }
}

From source file:util.Support.java

/**
 * Send email by SSL// ww  w . j  a  v a2  s.  c om
 *
 * @param toEmail Email of user
 * @param idActive id active authentication
 */
public static void sendMail(String toEmail, String idActive) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(util.Constants.FROM_EMAIL, util.Constants.PASSWORD_EMAIL);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(util.Constants.FROM_EMAIL));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject("Authentication registration your account.");
        if (!idActive.isEmpty()) {
            message.setText("Dear Mail Crawler," + "\n Click to link to complete the registered , please!"
                    + "\n http://localhost:8084/JudiBlog/active?id=" + idActive + "");
        } else {
            message.setText("OK, thank you!" + "\n You have registed successfully!");
        }
        Transport.send(message);

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

From source file:org.forumj.email.FJEMail.java

public static void sendMail(String to, String from, String host, String subject, String text)
        throws ConfigurationException, AddressException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    String mailDebug = FJConfiguration.getConfig().getString("mail.debug");
    props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
    Session session = Session.getInstance(props);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = { new InternetAddress(to) };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.addHeader("charset", "UTF-8");
    msg.setSubject(subject);//from   w w w  . j ava 2  s.co  m
    msg.setSentDate(new Date());
    msg.setDataHandler(new DataHandler(new HTMLDataSource(text)));
    Transport.send(msg);
}

From source file:com.liferay.util.mail.MailEngine.java

public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
        String subject, String body, boolean htmlFormat) throws MailEngineException {

    long start = System.currentTimeMillis();

    try {//from  w w w  .  java 2s  .  c  om
        Session session = getSession();

        Message msg = new MimeMessage(session);

        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, to);

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

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

        msg.setSubject(subject);

        /*BodyPart bodyPart = new MimeBodyPart();
                
        if (htmlFormat) {
           bodyPart.setContent(body, "text/html");
        }
        else {
           bodyPart.setText(body);
        }
                
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
                
        msg.setContent(multipart);*/

        if (htmlFormat) {
            msg.setContent(body, _TEXT_HTML);
        } else {
            msg.setContent(body, _TEXT_PLAIN);
        }

        _sendMessage(session, msg);
    } catch (SendFailedException sfe) {
        _log.error("From: " + from);
        _log.error("To: " + to);
        _log.error("Subject: " + subject);
        _log.error("Body: " + body);

        Logger.error(MailEngine.class, sfe.getMessage(), sfe);
    } catch (Exception e) {
        throw new MailEngineException(e);
    }

    long end = System.currentTimeMillis();

    _log.debug("Sending mail takes " + (end - start) + " seconds");
}

From source file:com.mnt.base.mail.MailHelper.java

public static void sendMail(String mailType, String mailTos, Map<String, Object> infoMap) {

    String[] mailtemplate = loadMailTemplate(mailType);

    if (mailtemplate != null && mailtemplate.length == 2) {
        String from = BaseConfiguration.getProperty("mail_server_email");
        String subject = buildMailContent(mailtemplate[0], infoMap, false);
        String mailContent = buildMailContent(mailtemplate[1], infoMap, true);

        Message msg = new MimeMessage(smtpSession);
        try {//from   w w  w .  j av a2s  .  c  om
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTos, false));
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            msg.setContent(mailContent, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());

            Transport.send(msg);
        } catch (Exception e) {
            log.error("fail to send the mail: " + msg, e);
        }
    }
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//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);
        }//www  .ja  v  a2  s.co  m
    });

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

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

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

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

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

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

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

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

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   www  . j  ava 2s . c  o m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Su solicitud de recuperacin de contrasea ha sido procesada. Su usuario y contrasea para acceder a la plataforma de adopciones son los siguientes:"
                + "\n\n Usuario: " + user + "\n\n Contrasea: " + pass_plano + "\n\n Saludos cordiales, ");

        Transport.send(message);

    } catch (Exception ex) {

    }

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

From source file:org.vulpe.commons.util.VulpeEmailUtil.java

/**
 * Send mail to recipients by Web Service.
 *
 * @param recipients//from  w w w .java2s  . c  om
 *
 * @param subject
 *
 * @param body
 *
 * @param mailerService
 *
 * @throws VulpeSystemException
 *             exception
 */
public static void sendMailByService(final String[] recipients, final String subject, final String body,
        final String mailerService) {
    try {
        final ResourceBundle bundle = ResourceBundle.getBundle("mail");
        String mailFrom = "";
        if (bundle.containsKey("mail.from")) {
            mailFrom = bundle.getString("mail.from");
        }
        final InitialContext initialContext = new InitialContext();
        final Session session = (Session) initialContext.lookup(mailerService);
        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailFrom));
        for (String recipient : recipients) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
        // msg.setRecipient(Message.RecipientType.TO, new
        // InternetAddress(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }

}

From source file:com.app.mail.DefaultMailSender.java

private static Message _populateContactMessage(String emailAddress, String messageBody, Session session)
        throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(emailAddress));

    message.addRecipient(Message.RecipientType.TO,
            new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS));

    message.setSubject("You Have A New Message From " + emailAddress);
    message.setText(messageBody);// w  w w.  ja v a2s  . c  o m

    return message;
}

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail2(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

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

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*www  .  ja v a2 s .  c o  m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Bienvenido al SISTEMA INFORM?TICO DEL REGISTRO NACIONAL DE ADOPCIONES, "
                + "sus credenciales para inscribirse al taller son las siguientes:" + "\n\n Usuario: " + user
                + "\n\n Contrasea: " + pass_plano
                //                    + "\n\n Para ingresar al sistema realizar lo siguiente, "
                //                    + "\n\n"
                //                    + "\n\n"
                //                    + "\n\n A. Click directamente en el siguiente link: "
                //                    + "\n\n"
                //                    + "\n\n       1. Click: http://app.mimp.gob.pe:8080/sirna "
                //                    + "\n\n       2. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n B. En caso no funcione el link, ingresar al sistema desde la pgina web: "
                //                    + "\n\n"
                //                    + "\n\n       1. Ingresar a la pgina web: www.mimp.gob.pe "
                //                    + "\n\n       2. En la barra de men Direcciones Generales? submen Vicemin. Pob. Vulnerables? seleccionar Adopciones? "
                //                    + "\n\n       3. Click en SIRNA Sistema Informtico del Registro Nacional de Adopciones? "
                //                    + "\n\n       4. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n A travs del SIRNA usted podr realizar las siguientes acciones: "
                //                    + "\n\n"
                //                    + "\n\n       - Inscribirse a uno de los talleres programados. "
                //                    + "\n\n       - Descargar las lecturas de su taller. "
                //                    + "\n\n       - Revisar el estado del proceso de adopcin. "
                //                    + "\n\n       - Cambiar su contrasea. "
                //                    + "\n\n"
                //                    + "\n\n Para continuar con el proceso, por favor ingresar al sistema e inscribirse a uno de los talleres programados, hasta un da antes de inicio del taller y/o las bacantes se  "
                //                    + "\n\n encuentres disponibles. "
                + "\n\n"
                + "\n\n De tener alguna complicacin y no fue posible su ingreso al sistema, comunicarse inmediatamente con la unidad de adopcin correspondiente.  "
                + "\n\n" + "\n\n Atentamente, " + "\n\n" + "\n\n Direccin General de Adopciones " + "\n\n"
                + "\n\n Ministerio de la Mujer y Poblaciones Vulnerables " + "\n\n ");

        Transport.send(message);

        /*  } catch (Exception ex) {
         */
    } catch (Exception ex) {

    }

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