Example usage for javax.mail.internet MimeMessage setSender

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

Introduction

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

Prototype

public void setSender(Address address) throws MessagingException 

Source Link

Document

Set the RFC 822 "Sender" header field.

Usage

From source file:com.jive.myco.seyren.core.service.notification.EmailNotificationService.java

private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException {

    MimeMessage mail = mailSender.createMimeMessage();
    InternetAddress senderAddress = new InternetAddress(email.getFrom());
    mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo()));
    mail.setSender(senderAddress);
    mail.setFrom(senderAddress);//from w w w .j  av  a  2  s  .c  o  m
    mail.setText(email.getMessage());
    mail.setSubject(email.getSubject());
    mail.addHeader("Content-Type", "text/html; charset=UTF-8");

    return mail;
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {//from   ww  w. j  a  va  2s.  c o m
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/*from   w  ww .  ja  v a 2 s .  co m*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void sendMail(MailTransport mailTransport) {
    log.debug("Mail delivery started");
    File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile();
    Properties config = new Properties();

    try {//from  w w  w .ja v a  2 s  . c o m
        config.load(new FileReader(propertyfile));
    } catch (IOException e) {
        log.error(e);
    }

    Session session = Session.getDefaultInstance(config);

    log.debug("Received session");

    MimeMessage message = new MimeMessage(session);

    String to = mailTransport.getTo();
    String from = mailTransport.getFrom();
    String replyTo = mailTransport.getReplyTo();
    String subject = mailTransport.getSubject();
    String html = mailTransport.getHtml();
    String text = mailTransport.getText();

    try {
        Address fromAdr = new InternetAddress(from);
        Address toAdr = new InternetAddress(to);
        Address rplyAdr = new InternetAddress(replyTo);

        message.setSubject(subject);
        message.setFrom(fromAdr);
        message.setRecipient(Message.RecipientType.TO, toAdr);
        message.setReplyTo(new Address[] { rplyAdr });
        message.setSender(fromAdr);
        message.addHeader("Return-path", replyTo);
        message.addHeader("X-TRV-MID", mailTransport.getmId());
        message.addHeader("X-TRV-UID", mailTransport.getuId());

        // Content
        MimeBodyPart messageTextPart = new MimeBodyPart();
        messageTextPart.setText(text);
        messageTextPart.setContent(html, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageTextPart);

        // Put parts in message
        message.setContent(multipart);

        log.debug("Dispatching message");
        Transport.send(message);
        log.debug("Mail delivery ended");
    } catch (MessagingException e) {
        log.error(e);
    }

}

From source file:org.jresponder.message.MessageRefImpl.java

/**
 * Render a message in the context of a particular subscriber
 * and subscription.//from w ww.  j  ava2s. co  m
 */
@Override
public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber,
        Subscription aSubscription) {

    try {

        // prepare context
        Map<String, Object> myRenderContext = new HashMap<String, Object>();
        myRenderContext.put("subscriber", aSubscriber);
        myRenderContext.put("subscription", aSubscription);
        myRenderContext.put("config", aSendConfig);
        myRenderContext.put("message", this);

        // render the whole file
        String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext);

        // now parse again with Jsoup
        Document myDocument = Jsoup.parse(myRenderedFileContents);

        String myHtmlBody = "";
        String myTextBody = "";

        // html body
        Elements myBodyElements = myDocument.select("#htmlbody");
        if (!myBodyElements.isEmpty()) {
            myHtmlBody = myBodyElements.html();
        }

        // text body
        Elements myJrTextBodyElements = myDocument.select("#textbody");
        if (!myJrTextBodyElements.isEmpty()) {
            myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first());
        }

        // now build the actual message
        MimeMessage myMimeMessage = aMimeMessage;
        // wrap it in a MimeMessageHelper - since some things are easier with that
        MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage);

        // set headers

        // subject
        myMimeMessageHelper.setSubject(TextRenderUtil.getInstance()
                .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext));

        // TODO: implement DKIM, figure out subetha

        String mySenderEmailPattern = aSendConfig.getSenderEmailPattern();
        String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext);
        myMimeMessage.setSender(new InternetAddress(mySenderEmail));

        myMimeMessageHelper.setTo(aSubscriber.getEmail());

        // from
        myMimeMessageHelper.setFrom(
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext),
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext));

        // see how to set body

        // if we have both text and html, then do multipart
        if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) {

            // create wrapper multipart/alternative part
            MimeMultipart ma = new MimeMultipart("alternative");
            myMimeMessage.setContent(ma);
            // create the plain text
            BodyPart plainText = new MimeBodyPart();
            plainText.setText(myTextBody);
            ma.addBodyPart(plainText);
            // create the html part
            BodyPart html = new MimeBodyPart();
            html.setContent(myHtmlBody, "text/html");
            ma.addBodyPart(html);
        }

        // if only HTML, then just use that
        else if (myHtmlBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myHtmlBody, true);
        }

        // if only text, then just use that
        else if (myTextBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myTextBody, false);
        }

        // if neither text nor HTML, then the message is being skipped,
        // so we just return null
        else {
            return false;
        }

        return true;

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.utils.PMUtils.java

public static void sendMail(String[] addresses, String subject, String message)
        throws UnsupportedEncodingException, MessagingException {

    MimeMessage mimeMessage = new MimeMessage(Mailer.descriptor().createSession());
    String adminAddress = JenkinsLocationConfiguration.get().getAdminAddress();

    InternetAddress[] to = new InternetAddress[addresses.length];
    for (int i = 0; i < addresses.length; i++) {
        to[i] = new InternetAddress(addresses[i], true);
    }//from   w w  w  . j a va2s  .c  o m
    mimeMessage.setSender(new InternetAddress(adminAddress));
    mimeMessage.setRecipients(Message.RecipientType.TO, to);
    mimeMessage.setSubject(subject, "ISO-2022-JP");
    mimeMessage.setText(message, "ISO-2022-JP");
    Transport.send(mimeMessage);
}

From source file:org.apache.james.core.builder.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()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }/*from  w w w  . java 2 s . com*/
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    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()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMimeMessage(String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setSubject(subject);//from  ww  w.  j  ava2  s  . c o  m
    message.setSender(new InternetAddress(USER));
    message.setRecipient(RecipientType.TO, new InternetAddress(SIEVE_LOCALHOST));
    message.saveChanges();
    return message;
}

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 w w  w  .jav  a  2s .c  o  m*/
        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.eurekaclinical.user.service.email.FreeMarkerEmailSender.java

/**
 * Send an email to the given email address with the given subject line,
 * using contents generated from the given template and parameters.
 *
 * @param templateName The name of the template used to generate the
 * contents of the email./*from   w  w w  .j a v a 2 s.co m*/
 * @param subject The subject for the email being sent.
 * @param emailAddress Sends the email to this address.
 * @param params The template is merged with these parameters to generate
 * the content of the email.
 * @throws EmailException Thrown if there are any errors in generating
 * content from the template, composing the email, or sending the email.
 */
private void sendMessage(final String templateName, final String subject, final String emailAddress,
        final Map<String, Object> params) throws EmailException {
    Writer stringWriter = new StringWriter();
    try {
        Template template = this.configuration.getTemplate(templateName);
        template.process(params, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new EmailException(e);
    }

    String content = stringWriter.toString();
    MimeMessage message = new MimeMessage(this.session);
    try {
        InternetAddress fromEmailAddress = null;
        String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress();
        if (fromEmailAddressStr != null) {
            fromEmailAddress = new InternetAddress(fromEmailAddressStr);
        }
        if (fromEmailAddress == null) {
            fromEmailAddress = InternetAddress.getLocalAddress(this.session);
        }
        if (fromEmailAddress == null) {
            try {
                fromEmailAddress = new InternetAddress(
                        "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName());
            } catch (UnknownHostException ex) {
                fromEmailAddress = new InternetAddress("no-reply@localhost");
            }
        }
        message.setFrom(fromEmailAddress);
        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
        message.setSender(fromEmailAddress);
        Transport.send(message);
    } catch (MessagingException e) {
        LOGGER.error("Error sending the following email message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            message.writeTo(out);
            out.close();
        } catch (IOException | MessagingException ex) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
        LOGGER.error(out.toString());
        throw new EmailException(e);
    }
}