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:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }//from   w w w . j av  a2 s.c om
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * //  w  w  w  . j ava  2 s  . c om
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:org.tsm.concharto.lab.LabJavaMail.java

private void sendConfirmationEmail(User user) {
    //mailSender.setHost("skipper");
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getEmail());/*from   w  ww. ja  v a2s  .c om*/
    String messageText = StringUtils.replace(WELCOME_MESSAGE, PARAM_NAME, user.getUsername());
    message.setText(messageText);
    message.setSubject(WELCOME_SUBJECT);
    message.setFrom("<Concharto Notifications> notify@concharto.com");

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    InternetAddress from = new InternetAddress();
    from.setAddress("notify@concharto.com");
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal("Concharto Notifications");
        mimeMessage.addRecipient(Message.RecipientType.TO, to);
        mimeMessage.setSubject(WELCOME_SUBJECT);
        mimeMessage.setText(messageText);
        mimeMessage.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mailSender.setHost("localhost");
    mailSender.send(mimeMessage);

    /*
    Confirm your registration with Concharto
            
    Hello sanmi,
            
    Welcome to the Concharto community!
            
    Please click on this link to confirm your registration: http://www.concharto.com/member/confirm.htm?id=:confirmation 
            
    You can find out more about us at http://wiki.concharto.com/wiki/About.
            
    If you were not expecting this email, just ignore it, no further action is required to terminate the request.
     */
}

From source file:org.apache.axis.transport.mail.MailWorker.java

/**
 * Send the soap request message to the server
 * //from   ww w.ja v a2 s .co  m
 * @param msgContext
 * @param smtpHost
 * @param sendFrom
 * @param replyTo
 * @param output
 * @throws Exception
 */
private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo,
        String subject, Message output) throws Exception {
    SMTPClient client = new SMTPClient();
    client.connect(smtpHost);

    // After connection attempt, you should check the reply code to verify
    // success.
    System.out.print(client.getReplyString());
    int reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    client.login(smtpHost);
    System.out.print(client.getReplyString());
    reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(sendFrom));
    msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo));
    msg.setDisposition(MimePart.INLINE);
    msg.setSubject(subject);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024);
    output.writeTo(out);
    msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants()));

    ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024);
    msg.writeTo(out2);

    client.setSender(sendFrom);
    System.out.print(client.getReplyString());
    client.addRecipient(replyTo);
    System.out.print(client.getReplyString());

    Writer writer = client.sendMessageData();
    System.out.print(client.getReplyString());
    writer.write(out2.toString());
    writer.flush();
    writer.close();

    System.out.print(client.getReplyString());
    if (!client.completePendingCommand()) {
        System.out.print(client.getReplyString());
        AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
        throw fault;
    }
    System.out.print(client.getReplyString());
    client.logout();
    client.disconnect();
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*w  w w . j a  va2s  .  co m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.apache.james.mailetcontainer.impl.JamesMailetContext.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition/*  ww  w .  ja v a 2  s.  com*/
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    // This sends a message to the james component that is a bounce of the
    // sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = new HashSet<MailAddress>();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Method responsible for sending a email to the user, including a link to
 * activate his user account.// www .j a va2 s . com
 * 
 * @param user
 *            User the activation mail should be sent to
 * @param serverString
 *            Name and port of the server the user was added.
 * @throws CannotSendMailException
 *             if the mail could not be sent
 */
public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Please confirm your Planningsuite user account");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("Please use the following link to confirm your Planningsuite user account: \n");
        builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Activation mail sent successfully to {}", user.getEmail());
    } catch (Exception e) {
        log.error("Error at sending activation mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e);
    }
}

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

@Test
public void testMultiSendMail() 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  w w w  . j  ava  2 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);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("homer.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("lisa.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("marge.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maggie.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("ned.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maude.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("rod.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("todd.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("krusty.theklown@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("selma.bouvier@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("patty.bouvier@silverpeas.com");
    externalUsers.add(user);
    assertThat(externalUsers.size(), is(12));
    notificationHelper.sendMail(mail, externalUsers);
    Iterator<ExternalUser> iter = externalUsers.iterator();
    while (iter.hasNext()) {
        ExternalUser recipient = iter.next();
        checkSimpleEmail(recipient.getEmail(), "Simple text Email test");
    }
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Sends the user a link to reset the password.
 * /*from   w  w w . j a  v  a 2  s  .com*/
 * @param user
 *            the user
 * @param serverString
 *            host and port of the server
 * @throws CannotSendMailException
 *             if the password reset mail could not be sent
 */
public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Planningsuite password recovery");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("You have requested help recovering the password for the Plato user ");
        builder.append(user.getUsername()).append(".\n\n");
        builder.append("Please use the following link to reset your Planningsuite password: \n");
        builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Sent password reset mail to " + user.getEmail());

    } catch (Exception e) {
        log.error("Error at sending password reset mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail());
    }
}

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

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

    String subjectModuleInformationsEmail = messageSource.getMessage("mail.subject.module.information", null,
            Locale.ENGLISH);/*from   www . j a va2  s .c  o m*/

    User user = (User) mapConfigEmail.get("user");
    Module module = (Module) mapConfigEmail.get("module");
    Configuration configuration = (Configuration) mapConfigEmail.get("configuration");
    MimeMessage message = (MimeMessage) mapConfigEmail.get("message");
    message.setSubject(subjectModuleInformationsEmail + ": " + module.getApplication().getName());
    mapConfigEmail.put("message", message);

    logger.info("define Email of module information ");
    logger.debug(
            "constructModuleInformationsBody parameters : User " + user.toString() + " Module : " + module);

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

    moduleInfos = module.getModuleInfos();
    mapVariables.put("userLogin", user.getLogin());
    mapVariables.put("userLastName", user.getLastName());
    mapVariables.put("userFirstName", user.getFirstName());

    Template template = null;
    try {
        mapVariables.put("module_seq", module.getInstanceNumber().toString());

        if (module.getName().contains("mysql")) {
            mapVariables.put("mysqlDatabase", moduleInfos.get("database"));
            mapVariables.put("mysqlPort", module.getListPorts().get("mysqlPort"));
            mapVariables.put("mysqlUser", moduleInfos.get("username"));
            mapVariables.put("mysqlPassword", moduleInfos.get("password"));
            mapVariables.put("internalDNSName", module.getInternalDNSName());
            template = configuration.getTemplate("emailModuleInformations-mysql.ftl");

        } else if (module.getName().contains("postgres")) {
            mapVariables.put("pgDatabase", moduleInfos.get("database"));
            mapVariables.put("pgAlias", moduleInfos.get("linkAlias"));
            mapVariables.put("pgPort", module.getListPorts().get("pgPort"));
            mapVariables.put("pgUser", moduleInfos.get("username"));
            mapVariables.put("pgPassword", moduleInfos.get("password"));

            mapVariables.put("internalDNSName", module.getInternalDNSName());

            template = configuration.getTemplate("emailModuleInformations-postgres.ftl");
        } else if (module.getName().contains("mongo")) {
            mapVariables.put("mongoDatabase", moduleInfos.get("database"));
            mapVariables.put("mongoAlias", moduleInfos.get("linkAlias"));
            mapVariables.put("mongoPort", module.getListPorts().get("mongoPort"));
            mapVariables.put("mongoUser", moduleInfos.get("username"));
            mapVariables.put("mongoPassword", moduleInfos.get("password"));
            mapVariables.put("internalDNSName", module.getInternalDNSName());
            template = configuration.getTemplate("emailModuleInformations-mongo.ftl");
        } else if (module.getName().contains("oracle-xe")) {
            mapVariables.put("oracleDatabase", moduleInfos.get("database"));
            mapVariables.put("oracleIP", module.getContainerIP());
            mapVariables.put("oraclePort", module.getListPorts().get("oraclePort"));
            mapVariables.put("oracleUser", moduleInfos.get("username"));
            mapVariables.put("oraclePassword", moduleInfos.get("password"));
            template = configuration.getTemplate("emailModuleInformations-oracle-xe.ftl");
        } else if (module.getName().contains("redis")) {
            mapVariables.put("redisPassword", module.getModuleInfos().get("password"));
            mapVariables.put("internalDNSName", module.getInternalDNSName());
            template = configuration.getTemplate("emailModuleInformations-redis.ftl");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("template : " + template);
        }
    } catch (IOException e) {
        logger.error("Error define Body method : config freemarker " + e);
    }

    mapConfigEmail.put("template", template);
    mapConfigEmail.put("mapVariables", mapVariables);

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

    return this.writeBody(mapConfigEmail);

}