Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*  www  .  j a va  2 s  .c o  m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {//from   ww  w.  j av a2s. c  om
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}

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 {//from  ww w  .  j a  v a2 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.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java

private void sendMessage(final String subject, final String content) {
    try {/*from   w  w w .  j  av a 2s . c om*/
        Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator)
                : Session.getInstance(smtpProps);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses));
        msg.setText(content, UTF_8.name(), "html");

        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", 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 {//from  ww  w. j av  a2 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:eu.planets_project.pp.plato.action.session.ExceptionAction.java

@RaiseEvent("exceptionHandled")
public String sendMail() {
    try {//from   ww  w . j  a  v a  2 s.  c  o m
        log.debug(body);
        Properties props = System.getProperties();
        Properties mailProps = new Properties();
        mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties"));
        props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER"));
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailProps.getProperty("FROM")));
        message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO")));
        String exceptionType = "Unknown";
        String exceptionMessage = "";
        String stackTrace = "";

        String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName();

        if (lastHandledException != null) {
            exceptionType = lastHandledException.getClass().getCanonicalName();
            exceptionMessage = lastHandledException.getMessage();
            StringWriter writer = new StringWriter();
            lastHandledException.printStackTrace(new PrintWriter(writer));
            stackTrace = writer.toString();
        }

        message.setSubject("[PlatoError] " + exceptionType + " at " + host);
        StringBuilder builder = new StringBuilder();
        builder.append("Date: " + format.format(new Date()) + "\n");
        builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n");
        builder.append("ExceptionType: " + exceptionType + "\n");
        builder.append("ExceptionMessage: " + exceptionMessage + "\n\n");

        builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n");
        builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n");
        builder.append(stackTrace);
        message.setText(builder.toString());
        message.saveChanges();
        Transport.send(message);
        this.lastHandledException = null;
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.",
                "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."));
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Bugreport couldn't be sent",
                "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. "
                        + "Please send an email to plato@ifs.tuwien.ac.at with a "
                        + "description of what you have been doing at the time of the error."
                        + "Thank you very much!"));
        return null;
    }
    return "home";
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {//from   w  w w.  j  a va 2  s.  c om
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);
    msg.setHeader(XMAILER, xmailer);//ww  w.j a v a  2  s  . co m
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

/**
 * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set
 * @return/*from   w  w w .  j ava 2 s. c  om*/
 * @throws Exception
 */
private MimeMessage preparePlainMimeMessage(InternetAddress internetAddressFrom, String subject,
        String plainBody, List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());
    if (attachments == null || attachments.isEmpty()) {
        msg.setText(plainBody, mailEncoding);
    } else {
        MimeMultipart mimeMultipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(plainBody, mailEncoding);
        mimeMultipart.addBodyPart(textBodyPart);

        if (attachments != null) {
            includeAttachments(mimeMultipart, attachments);
        }

        msg.setContent(mimeMultipart);
    }
    return msg;
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();//from www  .  j a va2 s.c  o m
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(mimeMessage, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}