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:org.apache.james.protocols.smtp.netty.NettyStartTlsSMTPServerTest.java

@Test
public void startTlsShouldWorkWhenUsingJavamail() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    server = createServer(createProtocol(Optional.<ProtocolHandler>of(hook)),
            Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
    server.bind();//from  w w w. j  a  v  a  2  s  .  co m
    SMTPTransport transport = null;

    try {
        InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", bindedAddress.getHostName());
        mailProps.put("mail.smtp.port", bindedAddress.getPort());
        mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName());
        mailProps.put("mail.smtp.socketFactory.fallback", "false");
        mailProps.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(mailProps);

        InternetAddress[] rcpts = new InternetAddress[] { new InternetAddress("valid@localhost") };
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

        transport = (SMTPTransport) mailSession.getTransport("smtps");

        transport.connect(new Socket(bindedAddress.getHostName(), bindedAddress.getPort()));
        transport.sendMessage(message, rcpts);

        assertThat(hook.getQueued()).hasSize(1);
    } finally {
        if (transport != null) {
            transport.close();
        }
    }
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {/*  www.j av  a 2  s . co  m*/
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java

/**
 * ??/*ww w.j a  va 2 s .co m*/
 * @param originator 
 * @param recipients ?
 * @param subject ??
 * @return 
 * @throws EnterpriseException ?
 */
private Message createMessage(final InternetAddress originator,
        final Map<RecipientType, InternetAddress> recipients, final String subject) throws EnterpriseException {
    Validate.isTrue(recipients.size() > 0);
    try {
        final MimeMessage message = new MimeMessage(session);
        if (originator != null) {
            message.setFrom(originator);
        }
        for (final Entry<RecipientType, InternetAddress> recipient : recipients.entrySet()) {
            message.addRecipient(recipient.getKey(), recipient.getValue());
        }
        message.setSubject(subject, CHARSET);
        return message;
    } catch (final MessagingException e) {
        throw new EnterpriseException(e);
    }
}

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

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?/* w  ww  . j  a  v  a2 s .  com*/
    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:hudson.tasks.MailSender.java

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

    msg.setSubject(getSubject(build, Messages.MailSender_BackToNormalMail_Subject(subject)), charset);
    StringBuilder buf = new StringBuilder();
    appendBuildUrl(build, buf);//from  w  w w .jav  a 2s  .  c om
    msg.setText(buf.toString(), charset);

    return msg;
}

From source file:tsuboneSystem.original.manager.MailManager.java

/**
 * ?//  www.ja  va  2 s.  c  o m
 * @return
 */
public boolean sendMail() {

    //???TRUE
    if (!check()) {
        return false;
    }
    Properties objPrp = new Properties();
    objPrp.setProperty("mail.smtp.host", "smtp.gmail.com");
    objPrp.setProperty("mail.smtp.port", "465");
    objPrp.setProperty("mail.smtp.auth", "true");

    //
    objPrp.setProperty("mail.smtp.connectiontimeout", "5000");
    objPrp.setProperty("mail.smtp.timeout", "5000");

    //???????????JavaMail?Message-ID?????
    objPrp.setProperty("mail.user", "kagucho.net@gmail.com");
    objPrp.setProperty("mail.host", "smtp.gmail.com");

    //????????
    objPrp.setProperty("mail.debug", "true");

    // SSL
    objPrp.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    objPrp.setProperty("mail.smtp.socketFactory.fallback", "false");
    objPrp.setProperty("mail.smtp.socketFactory.port", "465");

    String address = ConfigUtil.getConfig("mail.address");
    String pw = ConfigUtil.getConfig("mail.pw");

    // 
    Session session = Session.getInstance(objPrp, new PlainAuthenticator(address, pw));
    // ??
    MimeMessage objMsg = new MimeMessage(session);

    try {
        // ?
        objMsg.setFrom(new InternetAddress(address, displayName));

        // ??
        objMsg.setSubject(title, encoding);

        // ?TO????CCBCC?
        objMsg.setRecipients(Message.RecipientType.BCC, getToAddress());

        // 
        objMsg.setText(getContent(), encoding);

        // ?
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        try {
            t.connect("smtp.gmail.com", address, pw);
            t.sendMessage(objMsg, objMsg.getAllRecipients());
        } finally {
            t.close();
        }
        return false;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return true;
    } catch (MessagingException e) {
        e.printStackTrace();
        return true;
    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {//from   ww w  . j a  v a 2s .  c o m
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

@Override
public void send(final MailToSend mail) {
    SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings();

    MailAddress fromMailAddress = mail.getFrom();
    Session session = getMailSession(smtpConfiguration);
    try {/*w w w.  ja va2  s .co  m*/
        InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress();
        InternetAddress replyToAddress = null;
        List<InternetAddress[]> toAddresses = new ArrayList<>();

        // Parsing destination address for compliance with RFC822.
        final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList();
        for (ReceiverMailAddressSet addressBatch : addressBatches) {
            try {
                toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false));
            } catch (AddressException e) {
                SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                        "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e);
            }
        }
        try {
            if (mail.isReplyToRequired()) {
                replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false);
                if (StringUtil.isDefined(fromMailAddress.getName())) {
                    replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name());
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE",
                    "ReplyTo = " + fromMailAddress + " is malformed.", e);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        email.setSentDate(new Date());
        email.setSubject(mail.getSubject(), CharEncoding.UTF_8);
        mail.getContent().applyOn(email);

        // Sending.
        performSend(mail, smtpConfiguration, session, email, toAddresses);

    } catch (MessagingException | UnsupportedEncodingException e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:hudson.tasks.MailSender.java

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

    msg.setSubject(getSubject(build, Messages.MailSender_FailureMail_Subject()), charset);

    StringBuilder buf = new StringBuilder();
    appendBuildUrl(build, buf);//  www . ja  va 2  s. com

    boolean firstChange = true;
    for (ChangeLogSet.Entry entry : build.getChangeSet()) {
        if (firstChange) {
            firstChange = false;
            buf.append(Messages.MailSender_FailureMail_Changes()).append("\n\n");
        }
        buf.append('[');
        buf.append(entry.getAuthor().getFullName());
        buf.append("] ");
        String m = entry.getMsg();
        if (m != null) {
            buf.append(m);
            if (!m.endsWith("\n")) {
                buf.append('\n');
            }
        }
        buf.append('\n');
    }

    buf.append("------------------------------------------\n");

    try {
        // Restrict max log size to avoid sending enormous logs over email.
        // Interested users can always look at the log on the web server.
        List<String> lines = build.getLog(MAX_LOG_LINES);

        String workspaceUrl = null, artifactUrl = null;
        Pattern wsPattern = null;
        String baseUrl = Mailer.descriptor().getUrl();
        if (baseUrl != null) {
            // Hyperlink local file paths to the repository workspace or build artifacts.
            // Note that it is possible for a failure mail to refer to a file using a workspace
            // URL which has already been corrected in a subsequent build. To fix, archive.
            workspaceUrl = baseUrl + Util.encode(build.getProject().getUrl()) + "ws/";
            artifactUrl = baseUrl + Util.encode(build.getUrl()) + "artifact/";
            FilePath ws = build.getWorkspace();
            // Match either file or URL patterns, i.e. either
            // c:\hudson\workdir\jobs\foo\workspace\src\Foo.java
            // file:/c:/hudson/workdir/jobs/foo/workspace/src/Foo.java
            // will be mapped to one of:
            // http://host/hudson/job/foo/ws/src/Foo.java
            // http://host/hudson/job/foo/123/artifact/src/Foo.java
            // Careful with path separator between $1 and $2:
            // workspaceDir will not normally end with one;
            // workspaceDir.toURI() will end with '/' if and only if workspaceDir.exists() at time of call
            wsPattern = Pattern.compile("(" + Pattern.quote(ws.getRemote()) + "|"
                    + Pattern.quote(ws.toURI().toString()) + ")[/\\\\]?([^:#\\s]*)");
        }
        for (String line : lines) {
            line = line.replace('\0', ' '); // shall we replace other control code? This one is motivated by http://www.nabble.com/Problems-with-NULL-characters-in-generated-output-td25005177.html
            if (wsPattern != null) {
                // Perl: $line =~ s{$rx}{$path = $2; $path =~ s!\\\\!/!g; $workspaceUrl . $path}eg;
                Matcher m = wsPattern.matcher(line);
                int pos = 0;
                while (m.find(pos)) {
                    String path = m.group(2).replace(File.separatorChar, '/');
                    String linkUrl = artifactMatches(path, build) ? artifactUrl : workspaceUrl;
                    String prefix = line.substring(0, m.start()) + '<' + linkUrl + Util.encode(path) + '>';
                    pos = prefix.length();
                    line = prefix + line.substring(m.end());
                    // XXX better style to reuse Matcher and fix offsets, but more work
                    m = wsPattern.matcher(line);
                }
            }
            buf.append(line);
            buf.append('\n');
        }
    } catch (IOException e) {
        // somehow failed to read the contents of the log
        buf.append(Messages.MailSender_FailureMail_FailedToAccessBuildLog()).append("\n\n")
                .append(Functions.printThrowable(e));
    }

    msg.setText(buf.toString(), charset);

    return msg;
}

From source file:org.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email.//w  ww.  j a v  a 2  s  .  c o  m
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}