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

public void setSubject(String subject, String charset) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:hudson.tasks.MailSender.java

private MimeMessage createUnstableMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = createEmptyMail(build, listener);

    String subject = Messages.MailSender_UnstableMail_Subject();

    AbstractBuild<?, ?> prev = build.getPreviousBuild();
    boolean still = false;
    if (prev != null) {
        if (prev.getResult() == Result.SUCCESS)
            subject = Messages.MailSender_UnstableMail_ToUnStable_Subject();
        else if (prev.getResult() == Result.UNSTABLE) {
            subject = Messages.MailSender_UnstableMail_StillUnstable_Subject();
            still = true;/* w  w w .  java  2  s .  com*/
        }
    }

    msg.setSubject(getSubject(build, subject), charset);
    StringBuilder buf = new StringBuilder();
    // Link to project changes summary for "still unstable" if this or last build has changes
    if (still && !(build.getChangeSet().isEmptySet() && prev.getChangeSet().isEmptySet()))
        appendUrl(Util.encode(build.getProject().getUrl()) + "changes", buf);
    else
        appendBuildUrl(build, buf);
    msg.setText(buf.toString(), charset);

    return msg;
}

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();/*  ww  w. j  ava2  s.  com*/
            }
        }
    }
    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:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();// ww w .j av a 2s . c  o m
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * ????//from  w w w .  j av a 2 s .  co  m
 *
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
public void execute() throws UnsupportedEncodingException, MessagingException {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    final MimeMessage message = new MimeMessage(session);

    message.setFrom(fromAddress.toInternetAddress(charset));
    message.setReplyTo(toInternetAddresses(replyToAddressList));
    message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList));
    message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList));
    message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList));
    message.setSubject(subject, charset);

    setContent(message);

    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void applyMessageHeaders(final MimeMessage msg) throws Exception {

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

    if ((cc != null) && (cc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
    }/*from w  w  w .  ja v a  2 s .  com*/
    if ((bcc != null) && (bcc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
    }

    if (subject != null) {
        msg.setSubject(subject, LocaleHelper.getSystemEncoding());
    }

}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner//from  w w w  . j  a  va 2  s. c  o  m
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:org.jnap.core.email.Email.java

public void prepare(MimeMessage mimeMessage) throws Exception {
    final EmailAccountInfo acc = getAccountInfo();
    boolean multipart = StringUtils.isNotBlank(getHtmlText())
            || (getInlineResources() != null && getInlineResources().size() > 0)
            || (getAttachments() != null && getAttachments().size() > 0);

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
    if (acc.getFromName() != null) {
        helper.setFrom(acc.getFromEmailAddress(), acc.getFromName());
    } else {//ww  w .  j av a 2s .co m
        this.setFrom(acc.getFromEmailAddress());
    }
    helper.setTo(getTo());
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    mimeMessage.setSubject(getMessage(getSubject()), this.encoding);

    // sender info
    if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
        helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName()));
    } else {
        helper.setFrom(acc.getFromEmailAddress());
    }
    if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) {
        if (StringUtils.isNotBlank(acc.getReplyToName())) {
            helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName());
        } else {
            helper.setReplyTo(acc.getReplyToEmailAddress());
        }
    }

    final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText());
    final boolean hasText = StringUtils.isNotBlank(getText());
    if (hasHtmlText && hasText) {
        helper.setText(getText(), getHtmlText());
    } else if (hasHtmlText || hasText) {
        helper.setText(hasHtmlText ? getHtmlText() : getText());
    }

    // set headers
    final Map<String, String> mailHeaders = this.getHeaders();
    for (String header : mailHeaders.keySet()) {
        mimeMessage.addHeader(header, mailHeaders.get(header));
    }

    // add inline resources
    final Map<String, Resource> inlineRes = this.getInlineResources();
    if (inlineRes != null) {
        for (String cid : inlineRes.keySet()) {
            helper.addInline(cid, inlineRes.get(cid));
        }
    }
    // add attachments
    final Map<String, Resource> attachments = this.getAttachments();
    if (attachments != null) {
        for (String attachmentName : attachments.keySet()) {
            helper.addAttachment(attachmentName, attachments.get(attachmentName));
        }
    }
}

From source file:org.grouter.common.mail.MailHandler.java

/**
 * @param mimeMessage//from w  w w . j a  va 2s  .c  om
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
private void createHeader(MimeMessage mimeMessage, MailDto mailDto)
        throws UnsupportedEncodingException, MessagingException {

    //from
    InternetAddress fromAddress = new InternetAddress(mailDto.getFrom());
    fromAddress.setPersonal(mailDto.getSenderNote(), ENCODING);
    mimeMessage.setSender(fromAddress);

    //to

    List<String> senders = mailDto.getTo();
    InternetAddress[] toAddress = getRecipients(senders);

    List<String> sendersCc = mailDto.getCc();
    InternetAddress[] toAddressCc = getRecipients(sendersCc);

    List<String> sendersBcc = mailDto.getBcc();
    InternetAddress[] toAddressBcc = getRecipients(sendersBcc);

    mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
    mimeMessage.setRecipients(Message.RecipientType.CC, toAddressCc);
    mimeMessage.setRecipients(Message.RecipientType.BCC, toAddressBcc);

    //subject
    mimeMessage.setSubject(mailDto.getSubject(), ENCODING);

    //sent date
    mimeMessage.setSentDate(new Date());
}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {// ww  w  . j a va  2s  .c om
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public void sendMail(String from, String to, String subject, String messageText,
        Map<Object, Object> extraHeaders) {
    try {/*  w w w .j av a  2s . co  m*/
        MimeMessage msg = new MimeMessage(session);
        if (from.matches(EMAIL_PATTERN)) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // set fake from address; instead, add it as part of the message
            //msg.setFrom(new InternetAddress("invalid.email.address@mailinator.com"));
            msg.setFrom(getSystemAddress());
            messageText = "From: " + from + "\n\n" + messageText;
        }
        msg.setSentDate(new Date());
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(subject, charset);
        msg.setText(messageText, charset);

        if (extraHeaders != null) {
            for (Object key : extraHeaders.keySet()) {
                String headerName = key.toString();
                String headerValue = extraHeaders.get(key).toString();

                msg.addHeader(headerName, headerValue);
            }
        }

        Transport.send(msg);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}