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:au.org.paperminer.main.UserFilter.java

/**
 * Sends an email to the user asking they follow a link to validate their email address
 * @param id DB key to be embedded in response link
 * @param email Address target/*from   w  w  w  . ja v  a  2s.c  o m*/
 */
private void sendVerificationEmail(String id, String email, ServletRequest req) {
    m_logger.debug("sending mail");
    String from = "admin@" + m_serverName;
    Properties props = new Properties();
    props.put("mail.smpt.host", m_serverName);
    props.put("mail.from", from);
    Session session = Session.getInstance(props, null);
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, email);
        msg.setSubject("Verify your PaperMiner email address");
        msg.setSentDate(new Date());
        // FIXME: the verify address needs to be more robust
        msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n"
                + "PaperMiner has sent you this message to validate that the email address which you "
                + "supplied is able to receive notifications from our server.\n"
                + "To complete the verification process, please click the link below.\n\n" + "http://"
                + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n"
                + "If you are unable to click the link above, verification can be completed by copying "
                + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is "
                + email + ". Use this to log in when returning to the PaperMiner site.\n"
                + "You can update your email address, or change your TROVE API key at any time through the "
                + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n"
                + "Paper Miner Administrator");
        Transport.send(msg);
        m_logger.info("Verifcation mail sent to " + email);
    } catch (MessagingException ex) {
        m_logger.error("Email verification to " + email + " failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109");
    }
}

From source file:org.awknet.commons.mail.Mail.java

public void send() throws AddressException, MessagingException, FileNotFoundException, IOException {
    int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size();
    if (count == 0)
        return;/*w  w w.ja v a  2 s . com*/

    deleteDuplicates();

    Properties javaMailProperties = new Properties();

    if (fileName.equals("") || fileName == null)
        fileName = DEFAULT_PROPERTIES_FILE;

    javaMailProperties.load(getClass().getResourceAsStream(fileName));

    final String mailUsername = javaMailProperties.getProperty("mail.autentication.username");
    final String mailPassword = javaMailProperties.getProperty("mail.autentication.password");
    final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from");

    Session session = Session.getInstance(javaMailProperties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUsername, mailPassword);
        }
    });

    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray());
    msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray());
    msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray());
    msg.setSentDate(new Date());
    msg.setSubject(mailSubject);
    msg.setText(mailText, "UTF-8", "html");
    // msg.setText(mailText); //OLD WAY
    new Thread(new Runnable() {
        public void run() {
            try {
                Transport.send(msg);
                Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!");
            } catch (MessagingException ex) {
                Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex);
            }
        }
    }).start();
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMimeMessage(String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setSubject(subject);
    message.setSender(new InternetAddress(USER));
    message.setRecipient(RecipientType.TO, new InternetAddress(SIEVE_LOCALHOST));
    message.saveChanges();//from   w  w  w.ja  v a  2  s .  co  m
    return message;
}

From source file:org.libreplan.importers.notifications.ComposeMessage.java

public boolean composeMessageForUser(EmailNotification notification) {
    // Gather data about EmailTemplate needs to be used
    Resource resource = notification.getResource();
    EmailTemplateEnum type = notification.getType();
    Locale locale;//from   www  . ja v a  2  s . c  om
    Worker currentWorker = getCurrentWorker(resource.getId());

    UserRole currentUserRole = getCurrentUserRole(notification.getType());

    if (currentWorker != null && currentWorker.getUser().isInRole(currentUserRole)) {
        if (currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE)) {
            locale = new Locale(System.getProperty("user.language"));
        } else {
            locale = new Locale(currentWorker.getUser().getApplicationLanguage().getLocale().getLanguage());
        }

        EmailTemplate currentEmailTemplate = findCurrentEmailTemplate(type, locale);

        if (currentEmailTemplate == null) {
            LOG.error("Email template is null");
            return false;
        }

        // Modify text that will be composed
        String text = currentEmailTemplate.getContent();
        text = replaceKeywords(text, currentWorker, notification);

        String receiver = currentWorker.getUser().getEmail();

        setupConnectionProperties();

        final String username = usrnme;
        final String password = psswrd;

        // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
        Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Send message
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

            String subject = currentEmailTemplate.getSubject();
            message.setSubject(subject);

            message.setText(text);

            Transport.send(message);

            return true;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            if (receiver == null) {
                Messagebox.show(
                        _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
                        _("Error"), Messagebox.OK, Messagebox.ERROR);
            }
        }
    }
    return false;
}

From source file:org.cloudcoder.healthmonitor.HealthMonitor.java

private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews,
        boolean badNews, String reportEmailAddress) throws MessagingException, AddressException {
    Session session = createMailSession(config);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(reportEmailAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress));
    message.setSubject("CloudCoder health monitor report");

    StringBuilder body = new StringBuilder();
    body.append("<h1>CloudCoder health monitor report</h1>\n");

    if (badNews) {
        body.append("<h2>Unhealthy instances</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.badNews()) {
                appendReportItem(body, item, infoMap);
            }/* w  w  w .j a v  a 2 s  . co m*/
        }
        body.append("</ul>\n");
    }

    if (goodNews) {
        body.append("<h2>Healthy instances (back on line)</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.goodNews()) {
                appendReportItem(body, item, infoMap);
            }
        }
        body.append("</ul>\n");
    }

    message.setContent(body.toString(), "text/html");

    Transport.send(message);
}

From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java

/**
 * Send a single email.//from w w w.  j ava  2 s.  co  m
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*  w  ww  . ja  va 2s . c  o m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }/*from   w  ww.j a v a  2 s  .c o m*/

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox2(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS2));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS2).getInbox().add(message);
    }//from ww  w .  j  a va2 s .  c  om

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS2);
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void putMailInMailbox3(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
        final MimeMessage message = new MimeMessage((Session) null);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS3));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        MockMailbox.get(EMAIL_USER_ADDRESS3).getInbox().add(message);
    }//from  w  w w  .  j  a  v  a2  s .  c o  m

    logger.info("Putted " + messages + " into mailbox " + EMAIL_USER_ADDRESS3);
}