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: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   w w w. j a va2s.  c om
    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:ro.agrade.jira.qanda.listeners.DirectEmailMessageHandler.java

@Override
protected void sendMail(String[] recipients, String subject, String message, String from)
        throws MessagingException {

    SMTPMailServer server = mailServerManager.getDefaultSMTPMailServer();
    if (server == null) {
        LOG.debug("Email server is not configured. QandA is unable to send mails ...");
        return;//from   w  w w  .  j  ava 2 s  . c o m
    }
    LOG.debug("Email message: initializing.");
    //Set the host smtp address
    Properties props = new Properties();

    String proto = server.getMailProtocol().getProtocol();

    props.put("mail.transport.protocol", proto);
    props.put("mail." + proto + ".host", server.getHostname());
    props.put("mail." + proto + ".port", server.getPort());

    String username = server.getUsername();
    String password = server.getPassword();

    Authenticator auth = null;

    if (username != null && password != null) {
        auth = new SMTPAuthenticator(username, password);
        props.put("mail." + proto + ".auth", "true");
    }
    Session session;
    try {
        session = auth != null ? Session.getDefaultInstance(props, auth) : Session.getDefaultInstance(props);
    } catch (SecurityException ex) {
        LOG.warn("Could not get default session. Attempting to create a new one.");
        session = auth != null ? Session.getInstance(props, auth) : Session.getInstance(props);
    }

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

    if (from == null) {
        from = server.getDefaultFrom();
    }
    // set the from address
    if (from != null) {
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
    }

    if (recipients != null && recipients.length > 0) {
        // set TO address(es)
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
    }

    // Setting the Subject
    msg.setSubject(subject);

    // Setting text content
    MimeBodyPart contentPart = new MimeBodyPart();
    contentPart.setContent(message, "text/html; charset=utf-8");
    multipart.addBodyPart(contentPart);

    msg.setContent(multipart);
    Transport.send(msg);
    LOG.debug("Email message sent successfully.");
}

From source file:org.quartz.jobs.ee.mail.SendMailJob.java

protected MimeMessage prepareMimeMessage(MailInfo mailInfo) throws MessagingException {
    Session session = getMailSession(mailInfo);

    MimeMessage mimeMessage = new MimeMessage(session);

    Address[] toAddresses = InternetAddress.parse(mailInfo.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);

    if (mailInfo.getCc() != null) {
        Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc());
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
    }/*from   w w w. j  a v  a 2  s .  c  o m*/

    mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom()));

    if (mailInfo.getReplyTo() != null) {
        mimeMessage.setReplyTo(new InternetAddress[] { new InternetAddress(mailInfo.getReplyTo()) });
    }

    mimeMessage.setSubject(mailInfo.getSubject());

    mimeMessage.setSentDate(new Date());

    setMimeMessageContent(mimeMessage, mailInfo);

    return mimeMessage;
}

From source file:org.apache.mailet.base.test.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(text.get());/*from   www  .  j a v a  2  s  . com*/
        mimeMessage.setContent(bodyPart, "text/plain");
    }
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (from.isPresent()) {
        mimeMessage.setFrom(from.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }
    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        mimeMessage.addHeader(header.name, header.value);
    }
    mimeMessage.saveChanges();
    return mimeMessage;
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server// ww  w .  jav a 2s. c  o m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

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

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*  w  w  w . ja  v a  2 s .c  om*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.apache.axis.transport.mail.MailSender.java

/**
 * Send the soap request message to the server
 *
 * @param msgContext message context// w  w  w.ja v a 2s  . c  o  m
 *
 * @return id for the current message
 * @throws Exception
 */
private String writeUsingSMTP(MessageContext msgContext) throws Exception {
    String id = (new java.rmi.server.UID()).toString();
    String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST);

    SMTPClient client = new SMTPClient();
    client.connect(smtpHost);

    // After connection attempt, you should check the reply code to verify
    // success.
    System.out.print(client.getReplyString());
    int reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    client.login(smtpHost);
    System.out.print(client.getReplyString());
    reply = client.getReplyCode();
    if (!SMTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
        throw fault;
    }

    String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS);
    String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS);

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(fromAddress));
    msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress));

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message reqMessage = msgContext.getRequestMessage();

    msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"));
    msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action);
    msg.setDisposition(MimePart.INLINE);
    msg.setSubject(id);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024);
    reqMessage.writeTo(out);
    msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants()));

    ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024);
    msg.writeTo(out2);

    client.setSender(fromAddress);
    System.out.print(client.getReplyString());
    client.addRecipient(toAddress);
    System.out.print(client.getReplyString());

    Writer writer = client.sendMessageData();
    System.out.print(client.getReplyString());
    writer.write(out2.toString());
    writer.flush();
    writer.close();

    System.out.print(client.getReplyString());
    if (!client.completePendingCommand()) {
        System.out.print(client.getReplyString());
        AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
        throw fault;
    }
    System.out.print(client.getReplyString());
    client.logout();
    client.disconnect();
    return id;
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification//  www . j  av  a 2 s.  c  o m
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props);

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

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set the "Subject" header field.
        message.setSubject(subject);

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/* ww w.  j  a  v  a2s.c o m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendEmailMessageUser(final EmailMessageUser emailMessageUser) {
    try {
        if (!StringUtils.isBlank(emailMessageUser.getUser().getMail())) {
            //            SimpleMailMessage message = new SimpleMailMessage();
            //            message.setFrom(getMailFrom());
            //            message.setTo(emailMessageUser.getUser().getMail());
            //            message.setSubject(emailMessageUser.getSubject());
            //            message.setText(emailMessageUser.getBody());

            MimeMessagePreparator preparator = new MimeMessagePreparator() {

                @Override
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    mimeMessage.setFrom(new InternetAddress(getMailFrom()));
                    mimeMessage.setRecipient(Message.RecipientType.TO,
                            new InternetAddress(emailMessageUser.getUser().getMail()));
                    mimeMessage.setSubject(emailMessageUser.getSubject());
                    mimeMessage.setText(emailMessageUser.getBody(), "utf-8", "html");
                }
            };

            getJavaMailSender().send(preparator);
            emailMessageUser.setMailSended(Boolean.TRUE);
            emailMessageUser.setMailSendedDate(new Date());
            getEmailMessageUserDAO().merge(emailMessageUser);
        } else {
            logger.error("Email message not sended for user " + emailMessageUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + emailMessageUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:mitm.application.djigzo.james.matchers.SubjectTrigger.java

protected void removePattern(Mail mail, Matcher matcher) throws MessagingException, IOException {
    MimeMessage message = mail.getMessage();

    String subject = message.getSubject();

    /*//from w w  w . j av a 2s . c om
     * Store the subject in the Mail attributes before we remove the pattern from the subject. 
     * This will allow other mailets/matchers to get the original subject.
     * 
     * TODO: make the attribute under which the subject should be set, a parameter of the
     * matcher.
     */
    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    /*
     * Only set the original subject if it has not yet been set
     */
    if (mailAttributes.getOriginalSubject() == null) {
        mailAttributes.setOriginalSubject(subject);
    }

    subject = removePatternFromSubject(subject, matcher, 1);

    message.setSubject(subject);
}