Example usage for javax.mail.internet MimeMessage setReplyTo

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

Introduction

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

Prototype

@Override
public void setReplyTo(Address[] addresses) throws MessagingException 

Source Link

Document

Set the RFC 822 "Reply-To" header field.

Usage

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email//from ww  w  .  j  ava 2  s .com
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);//  www.  j a  v  a  2s  .co m

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

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:jease.cms.service.Mails.java

/**
 * Sends an email synchronously.//from  ww  w  .  j  a v a  2  s .  com
 */
public void send(String sender, String recipients, String subject, String text) throws MessagingException {
    if (properties != null) {
        Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) });
        message.setRecipients(Message.RecipientType.TO, recipients);
        message.setSubject(subject, "utf-8");
        message.setSentDate(new Date());
        message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        message.setHeader("Content-Transfer-Encoding", "quoted-printable");
        message.setText(text, "utf-8");
        Transport.send(message);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

public boolean send() {
    try {/*  www . j a va 2s .  co  m*/
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setReplyTo(new Address[] { replyToAddress });

        if (fromAddress == null) {
            msg.addFrom(new Address[] { replyToAddress });
        } else {
            msg.addFrom(new Address[] { fromAddress });
        }

        for (Recipient recipient : recipients) {
            msg.addRecipient(recipient.type, recipient.address);
        }

        msg.setSubject(subject);

        if (textContent.isEmpty()) {
            if (htmlContent.isEmpty()) {
                log.error("Message has neither text body nor HTML body");
            } else {
                msg.setContent(htmlContent, "text/html");
            }
        } else {
            if (htmlContent.isEmpty()) {
                msg.setContent(textContent, "text/plain");
            } else {
                MimeMultipart content = new MimeMultipart("alternative");
                addBodyPart(content, textContent, "text/plain");
                addBodyPart(content, htmlContent, "text/html");
                msg.setContent(content);
            }
        }

        msg.setSentDate(new Date());

        Transport.send(msg);
        return true;
    } catch (MessagingException e) {
        log.error("Failed to send message.", e);
        return false;
    }
}

From source file:edu.washington.iam.tools.IamMailSender.java

private MimeMessage genMimeMessage(IamMailMessage msg) {
    MimeMessage mime = mailSender.createMimeMessage();
    try {//  www.  ja  v a 2  s  . c om
        mime.setRecipients(RecipientType.TO, InternetAddress.parse(msg.getTo()));
        mime.setSubject(msg.makeSubstitutions(msg.getSubject()));
        mime.setReplyTo(InternetAddress.parse(replyTo));
        mime.setFrom(new InternetAddress(msg.getFrom()));
        mime.addHeader("X-Auto-Response-Suppress", "NDR, OOF, AutoReply");
        mime.addHeader("Precedence", "Special-Delivery, never-bounce");
        mime.setText(msg.makeSubstitutions(msg.getText()));
    } catch (MessagingException e) {
        log.error("iam mail build fails: " + e);
    }
    return mime;
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {//w w w  .j av  a  2  s .c  o  m
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format).// w  ww.  j a  va 2  s .com
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:io.mapzone.arena.share.app.EMailSharelet.java

private void sendEmail(final String toText, final String subjectText, final String messageText,
        final boolean withAttachment, final ImagePngContent image) throws Exception {
    MimeMessage msg = new MimeMessage(mailSession());

    msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false));
    // TODO we need the FROM from the current user
    msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );
    msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );

    msg.setSubject(subjectText, "utf-8");
    if (withAttachment) {
        // add mime multiparts
        Multipart multipart = new MimeMultipart();

        BodyPart part = new MimeBodyPart();
        part.setText(messageText);// w w  w  . j av a 2s .c o m
        multipart.addBodyPart(part);

        // Second part is attachment
        part = new MimeBodyPart();
        part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource))));
        part.setFileName("preview.png");
        part.setHeader("Content-ID", "preview");
        multipart.addBodyPart(part);

        // // third part in HTML with embedded image
        // part = new MimeBodyPart();
        // part.setContent( "<img src='cid:preview'>", "text/html" );
        // multipart.addBodyPart( part );

        msg.setContent(multipart);
    } else {
        msg.setText(messageText, "utf-8");
    }
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

private void addReplyTo(MimeMessage mimeMessage, String replyTo) throws MessagingException {
    if (null != replyTo && replyTo.length() > 0) {
        List<Address> replyTos = new ArrayList<Address>();
        for (String part : replyTo.split("[,;\\s]")) {
            String address = part.trim();
            if (address.length() > 0) {
                replyTos.add(new InternetAddress(address));
            }//from  w ww.  j ava  2  s  .  co  m
        }
        mimeMessage.setReplyTo(replyTos.toArray(new Address[replyTos.size()]));
    }
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

/**
 * Build a {@link MimeMessage} instance from the set of supplied parameters.
 * @return The {@link MimeMessage} instance;
 * @throws MessagingException//w ww  . ja v a2  s .  c  o m
 * @throws UnsupportedEncodingException
 */
public MimeMessage buildMimeMessage() throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());

    setJenkinsInstanceIdent(msg);

    msg.setContent("", contentType());
    if (StringUtils.isNotBlank(from)) {
        msg.setFrom(toNormalizedAddress(from));
    }
    msg.setSentDate(new Date());

    addSubject(msg);
    addBody(msg);
    addRecipients(msg);

    if (!replyTo.isEmpty()) {
        msg.setReplyTo(toAddressArray(replyTo));
    }
    return msg;
}