Example usage for javax.mail.internet MimeMessage setSentDate

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

Introduction

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

Prototype

@Override
public void setSentDate(Date d) throws MessagingException 

Source Link

Document

Set the RFC 822 "Date" header field.

Usage

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }/*from w ww .  j a v  a 2  s  .com*/

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail
 * // w  ww .j  ava  2 s.  co  m
 * @param mail The original Mail object
 * @param session Mail session
 * @return The MIME message
 */
private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    // this will also check for email error
    InternetAddress from = new InternetAddress(mail.getFrom());
    String recipients = mail.getHeader("To");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getTo();
    } else {
        recipients = mail.getTo() + "," + recipients;
    }
    InternetAddress[] to = toInternetAddresses(recipients);
    recipients = mail.getHeader("Cc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getCc();
    } else {
        recipients = mail.getCc() + "," + recipients;
    }
    InternetAddress[] cc = toInternetAddresses(recipients);
    recipients = mail.getHeader("Bcc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getBcc();
    } else {
        recipients = mail.getBcc() + "," + recipients;
    }
    InternetAddress[] bcc = toInternetAddresses(recipients);

    if ((to == null) && (cc == null) && (bcc == null)) {
        LOGGER.info("No recipient -> skipping this email");
        return null;
    }

    MimeMessage message = new MimeMessage(session);
    message.setSentDate(new Date());
    message.setFrom(from);

    if (to != null) {
        message.setRecipients(javax.mail.Message.RecipientType.TO, to);
    }

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

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

    message.setSubject(mail.getSubject(), EMAIL_ENCODING);

    for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) {
        message.setHeader(header.getKey(), header.getValue());
    }

    if (mail.getHtmlPart() != null || mail.getAttachments() != null) {
        Multipart multipart = createMimeMultipart(mail, context);
        message.setContent(multipart);
    } else {
        message.setText(mail.getTextPart());
    }

    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }/* w w w.j  av  a  2 s. c o  m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.anteam.alert.email.service.EmailAntlert.java

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?/*from w ww.  jav a  2  s .  c o m*/
    mimeMsg = new javax.mail.internet.MimeMessage(mailSession);

    try {
        // ?
        mimeMsg.setFrom(sender);
        // 
        mimeMsg.setRecipients(RecipientType.TO, receivers);
        // 
        mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET);

        // 
        MimeBodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBody);
        mimeMsg.setContent(multipart);

        // ??
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        // ??
        Transport.send(mimeMsg);
    } catch (MessagingException e) {
        logger.error("???", e);
        return false;
    }
    return true;
}

From source file:org.apache.james.James.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
 *
 * @return the bounce mail/*  w  w w.jav  a 2  s  . c  o m*/
 *
 * @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 recipients = new HashSet();
    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:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /* www.  j  av a 2s  .  c  om*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/* w w w.jav  a 2s . com*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;//from   ww w. j av a  2 s  .  c  o m
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:com.zimbra.cs.service.FeedManager.java

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr,
        Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext();) {
            if (it.next().getLocation() == null) {
                it.remove();/*from w  w  w .  j av a  2s. co m*/
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();

    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }

    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);

        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }

        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    msg.setContent("", "text/plain");
    msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset));
    msg.setSentDate(new Date());

    String replyTo = Mailer.descriptor().getReplyToAddress();
    if (StringUtils.isNotBlank(replyTo)) {
        msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) });
    }//from   w  w w  .  j a  v a 2 s.c  om

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    String defaultSuffix = Mailer.descriptor().getDefaultSuffix();
    StringTokenizer tokens = new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(),
                    AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address

            // if not a valid address (i.e. no '@'), then try adding suffix
            if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
                address += defaultSuffix;
            }

            try {
                rcp.add(Mailer.StringToAddress(address, charset));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                listener.getLogger().println("Unable to send to address: " + address);
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    for (AbstractProject project : includeUpstreamCommitters) {
        includeCulpritsOf(project, build, listener, rcp);
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}