Example usage for javax.mail.internet MimeMessage setSubject

List of usage examples for javax.mail.internet MimeMessage setSubject

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setSubject.

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void download(String type, String version, String token, String subject, String fromUser,
        String fromName, final String toUser, final String toName, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}",
                    new Object[] { type, version, token }).getMessage());
    model.put("name", toName);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8",
            model);//  w w w.j a  v a2  s  .  c  o  m

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:org.overlord.sramp.governance.services.NotificationResourceTest.java

@Test
public void testMail() {
    try {// w  ww .jav  a2  s. co m
        mailServer = SimpleSmtpServer.start(smtpPort);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
        properties.setProperty("mail.smtp.port", String.valueOf(smtpPort)); //$NON-NLS-1$
        Session mailSession = Session.getDefaultInstance(properties);
        MimeMessage m = new MimeMessage(mailSession);
        Address from = new InternetAddress("me@gmail.com"); //$NON-NLS-1$
        Address[] to = new InternetAddress[1];
        to[0] = new InternetAddress("dev@mailinator.com"); //$NON-NLS-1$
        m.setFrom(from);
        m.setRecipients(Message.RecipientType.TO, to);
        m.setSubject("test"); //$NON-NLS-1$
        m.setContent("test", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
        Transport.send(m);

        Assert.assertTrue(mailServer.getReceivedEmailSize() > 0);
        @SuppressWarnings("rawtypes")
        Iterator iter = mailServer.getReceivedEmail();
        while (iter.hasNext()) {
            SmtpMessage email = (SmtpMessage) iter.next();
            System.out.println(email.getBody());
            Assert.assertEquals("test", email.getBody()); //$NON-NLS-1$
        }

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        mailServer.stop();
    }

}

From source file:org.wso2.carbon.apimgt.core.impl.NewApiVersionMailNotifier.java

@Override
public void sendNotifications(NotificationDTO notificationDTO) throws APIManagementException {

    Properties props = notificationDTO.getProperties();
    //get Notifier email List
    Set<String> emailList = getEmailNotifierList(notificationDTO);

    if (emailList.isEmpty()) {
        log.debug("Email Notifier Set is Empty");
        return;//from w ww  .  j a  va2s  . c om
    }
    for (String mail : emailList) {
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session mailSession = Session.getDefaultInstance(props, auth);
            MimeMessage message = new MimeMessage(mailSession);
            notificationDTO.setTitle((String) notificationDTO.getProperty(NotifierConstants.TITLE_KEY));
            notificationDTO.setMessage((String) notificationDTO.getProperty(NotifierConstants.TEMPLATE_KEY));
            notificationDTO = loadMailTemplate(notificationDTO);
            message.setSubject(notificationDTO.getTitle());
            message.setContent(notificationDTO.getMessage(), NotifierConstants.TEXT_TYPE);
            message.setFrom(new InternetAddress(mailConfigurations.getFromUser()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
            Transport.send(message);
        } catch (MessagingException e) {
            log.error("Exception Occurred during Email notification Sending", e);
        }

    }
}

From source file:com.silverpeas.mailinglist.service.notification.TestNotificationHelper.java

@Test
public void testSimpleSendMail() throws Exception {
    MimeMessage mail = new MimeMessage(notificationHelper.getSession());
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { theSimpsons });
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);/*from   www  .  j  a v  a 2s . co  m*/
    List<ExternalUser> externalUsers = new LinkedList<ExternalUser>();
    ExternalUser user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("bart.simpson@silverpeas.com");
    externalUsers.add(user);
    notificationHelper.sendMail(mail, externalUsers);
    checkSimpleEmail("bart.simpson@silverpeas.com", "Simple text Email test");
}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override/*from  ww  w .  j av a2 s  .c  o  m*/
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

From source file:com.silverpeas.mailinglist.service.notification.AdvancedNotificationHelperTest.java

public void testSimpleSendMail() throws Exception {
    MimeMessage mail = new MimeMessage(notificationHelper.getSession());
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { theSimpsons });
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);//from  ww  w.  ja va2 s . co  m
    List<ExternalUser> externalUsers = new LinkedList<ExternalUser>();
    ExternalUser user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("bart.simpson@silverpeas.com");
    externalUsers.add(user);
    notificationHelper.sendMail(mail, externalUsers);
    checkSimpleEmail("bart.simpson@silverpeas.com", "Simple text Email test");
}

From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {

    String passwordDesencriptada = Desencriptar(password2);

    try {//from   www.  ja  va 2 s.  c om
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ha recibido tu solicitud. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + passwordDesencriptada + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

private Map<String, Object> constructChangeEmail(Map<String, Object> mapConfigEmail) throws MessagingException {

    String subjectChangeEmail = messageSource.getMessage("mail.subject.change.email", null, Locale.ENGLISH);

    Map<String, String> mapVariables = new HashMap<>();

    User user = (User) mapConfigEmail.get("user");
    Configuration configuration = (Configuration) mapConfigEmail.get("configuration");
    MimeMessage message = (MimeMessage) mapConfigEmail.get("message");
    message.setSubject(subjectChangeEmail);
    mapConfigEmail.put("message", message);

    logger.info("define Email of change of Email ");
    logger.debug("defineChangeEmailBody parameter : User " + user.toString());

    mapVariables.put("userLogin", user.getLogin());
    mapVariables.put("userEmail", user.getEmail());

    Template template = null;//w w  w  . j  a  v a 2s.  c om
    try {
        template = configuration.getTemplate("emailChangeMail.ftl");

    } catch (IOException e) {
        logger.error("Error define change Email's Body : config freemarker " + e);
    }
    mapConfigEmail.put("template", template);
    mapConfigEmail.put("mapVariables", mapVariables);

    logger.info("Variables inject in Email's body successfully to " + user.getEmail());

    return this.writeBody(mapConfigEmail);
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

private Map<String, Object> constructSendPasswordEmail(Map<String, Object> mapConfigEmail)
        throws MessagingException {

    String subjectSendPassword = messageSource.getMessage("mail.subject.send.password", null, Locale.ENGLISH);

    Map<String, String> mapVariables = new HashMap<>();

    User user = (User) mapConfigEmail.get("user");
    Configuration configuration = (Configuration) mapConfigEmail.get("configuration");
    MimeMessage message = (MimeMessage) mapConfigEmail.get("message");
    message.setSubject(subjectSendPassword);
    mapConfigEmail.put("message", message);

    logger.info("send password ");
    logger.debug("send password : User " + user.toString());

    mapVariables.put("userLogin", user.getLogin());
    mapVariables.put("userPassword", user.getPassword());

    Template template = null;//  w  ww.j  a va2s .c o  m
    try {
        template = configuration.getTemplate("sendPassword.ftl");

    } catch (IOException e) {
        logger.error("Error define sendPassword's Body : config freemarker " + e);
    }
    mapConfigEmail.put("template", template);
    mapConfigEmail.put("mapVariables", mapVariables);

    logger.info("Variables inject in Email's body successfully to " + user.getEmail());

    return this.writeBody(mapConfigEmail);

}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

private Map<String, Object> constructActivationEmail(Map<String, Object> mapConfigEmail)
        throws MessagingException {

    String subjectActivationEmail = messageSource.getMessage("mail.subject.activation", null, Locale.ENGLISH);

    Map<String, String> mapVariables = new HashMap<>();

    User user = (User) mapConfigEmail.get("user");
    Configuration configuration = (Configuration) mapConfigEmail.get("configuration");
    MimeMessage message = (MimeMessage) mapConfigEmail.get("message");
    message.setSubject(subjectActivationEmail);
    mapConfigEmail.put("message", message);

    logger.info("define Email of activation Email ");
    logger.debug("defineActivationBody parameter : User " + user.toString());

    mapVariables.put("userLogin", user.getLogin());
    mapVariables.put("userLastName", user.getLastName());
    mapVariables.put("userFirstName", user.getFirstName());
    mapVariables.put("userPassword", user.getPassword());
    mapVariables.put("userEmail", user.getEmail());

    Template template = null;//from  w  ww  . ja  v a2  s  .  com
    try {
        template = configuration.getTemplate("emailActivation.ftl");

    } catch (IOException e) {
        logger.error("Error define activation Email's Body : config freemarker " + e);
    }
    mapConfigEmail.put("template", template);
    mapConfigEmail.put("mapVariables", mapVariables);

    logger.info("Variables inject in Email's body successfully to " + user.getEmail());

    return this.writeBody(mapConfigEmail);
}