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.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*from  w ww  . ja  va2 s  .com*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

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

@Test
public final void testCapabilityExtraArguments() throws Exception {
    MimeMessage message = prepareMimeMessage("CAPABILITY");
    Mail mail = createUnauthenticatedMail(message);
    message.setSubject("CAPABILITY extra");
    message.saveChanges();/*from w ww .j  av  a2 s.c om*/
    mailet.service(mail);
    ensureResponse("Re: CAPABILITY extra", "NO \"Too many arguments: extra\"");
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email,
        List<ApplicationGroup> appGroups) throws IOException, MessagingException {

    StringBuilder body = new StringBuilder();
    body.append(/* w  w  w. j  a v  a 2  s.co m*/
            "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n"
                    + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}"
                    + "</style></head>");
    List<MimeBodyPart> mimeBodyParts = Lists.newArrayList();
    int index = 0;
    String subject = "";
    for (ApplicationGroup appGroup : appGroups) {
        boolean hasData = false;
        for (String prodName : appGroup.data.keySet()) {
            if (config.productService.getProductByName(prodName) == null)
                continue;
            hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0;
            if (hasData)
                break;
        }
        if (!hasData)
            continue;

        try {
            MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body);
            index++;
            if (mimeBodyPart != null) {
                mimeBodyParts.add(mimeBodyPart);
                subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName();
            }
        } catch (Exception e) {
            logger.error("Error contructing email", e);
        }
    }
    body.append("</html>");

    if (mimeBodyParts.size() == 0)
        return;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)),
            formatter.print(end));
    String toEmail = test ? testEmail : email;
    Session session = Session.getInstance(new Properties());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail);
    if (!test && !StringUtils.isEmpty(bccEmail)) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail);
    }
    MimeMultipart mimeMultipart = new MimeMultipart();
    BodyPart p = new MimeBodyPart();
    p.setContent(body.toString(), "text/html");
    mimeMultipart.addBodyPart(p);

    for (MimeBodyPart mimeBodyPart : mimeBodyParts)
        mimeMultipart.addBodyPart(mimeBodyPart);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.writeTo(outputStream);
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

    SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
    rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail));
    rawEmailRequest.setSource(fromEmail);
    logger.info("sending email to " + toEmail + " " + body.toString());
    emailService.sendRawEmail(rawEmailRequest);
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *//*from ww w .j a v a  2 s  . c  o  m*/
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from  w  w w  .  ja va 2s  .co  m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }/*from  ww  w .ja va2s  .co m*/

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

From source file:edu.cornell.mannlib.vitro.webapp.utils.MailUtil.java

public void sendMessage(String messageText, String subject, String from, String to, List<String> deliverToArray)
        throws IOException {

    Session s = FreemarkerEmailFactory.getEmailSession(req);

    try {/*from ww  w  .j  a  va 2  s. c o m*/

        int recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size();
        if (recipientCount == 0) {
            log.error("To establish the Contact Us mail capability the system administrators must  "
                    + "specify at least one email address in the current portal.");
        }

        MimeMessage msg = new MimeMessage(s);
        // Set the from address
        msg.setFrom(new InternetAddress(from));

        // Set the recipient address

        if (recipientCount > 0) {
            InternetAddress[] address = new InternetAddress[recipientCount];
            for (int i = 0; i < recipientCount; i++) {
                address[i] = new InternetAddress(deliverToArray.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        }

        // Set the subject and text
        msg.setSubject(subject);

        // add the multipart to the message
        msg.setContent(messageText, "text/html");

        // set the Date: header
        msg.setSentDate(new Date());
        Transport.send(msg); // try to send the message via smtp - catch error exceptions
    } catch (Exception ex) {
        log.error("Exception sending message :" + ex.getMessage(), ex);
    }
}

From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java

public static void Send(final String username, final String password, String recipientEmail, String ccEmail,
        String title, String message) throws AddressException, MessagingException {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }//from  w ww . jav  a  2 s.co  m

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {//w  w w .j a v a 2  s .  c o  m
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

                // Get system properties
                Properties properties = new Properties();

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

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

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

                    // Set To: header field of the header.
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

                    // Set Subject: header field
                    message.setSubject(conf.getMailSubject());

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }/*from  w  w w  .j a v  a2s .c o m*/
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}