Example usage for javax.mail.internet MimeMessage setText

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

Introduction

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

Prototype

@Override
public void setText(String text, String charset) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain" and the specified charset.

Usage

From source file:hudson.tasks.MailSender.java

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

    String subject = Messages.MailSender_UnstableMail_Subject();

    AbstractBuild<?, ?> prev = build.getPreviousBuild();
    boolean still = false;
    if (prev != null) {
        if (prev.getResult() == Result.SUCCESS)
            subject = Messages.MailSender_UnstableMail_ToUnStable_Subject();
        else if (prev.getResult() == Result.UNSTABLE) {
            subject = Messages.MailSender_UnstableMail_StillUnstable_Subject();
            still = true;//from w  w  w . j  a  va  2 s.c  o  m
        }
    }

    msg.setSubject(getSubject(build, subject), charset);
    StringBuilder buf = new StringBuilder();
    // Link to project changes summary for "still unstable" if this or last build has changes
    if (still && !(build.getChangeSet().isEmptySet() && prev.getChangeSet().isEmptySet()))
        appendUrl(Util.encode(build.getProject().getUrl()) + "changes", buf);
    else
        appendBuildUrl(build, buf);
    msg.setText(buf.toString(), charset);

    return msg;
}

From source file:org.opencastproject.messages.MailService.java

/** Message -> MimeMessage. */
private MimeMessage toMimeMessage(Mail mail) throws Exception {
    final MimeMessage msg = smtpService.createMessage();
    for (EmailAddress reply : mail.getReplyTo())
        msg.setReplyTo(new Address[] { new InternetAddress(reply.getAddress(), reply.getName(), "UTF-8") });

    // recipient//from ww  w . ja  v  a 2s  .  com
    for (EmailAddress recipient : mail.getRecipients()) {
        msg.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(recipient.getAddress(), recipient.getName(), "UTF-8"));
    }

    // subject
    msg.setSubject(mail.getSubject());

    EmailAddress from = mail.getSender();
    msg.setFrom(new InternetAddress(from.getAddress(), from.getName(), "UTF-8"));
    // body
    msg.setText(mail.getBody(), "UTF-8");
    return msg;
}

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);/*from  w  w w  .  ja v a2 s. co  m*/
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

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);//from   ww  w.  ja  va 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:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??//from   w ww . j av a  2 s. c  o  m
 * 
 * @param config javelin.properties???
 * @param entry ??
 * @return ???
 * @throws MessagingException ??????
 */
protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry)
        throws MessagingException {
    // JavaMail???
    Properties props = System.getProperties();
    String smtpServer = this.config_.getSmtpServer();
    if (smtpServer == null || smtpServer.length() == 0) {
        LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED);
        String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified";
        String messageDetail = CommunicatorMessages.getMessage(detailMessageKey);

        throw new MessagingException(messageDetail);
    }
    props.setProperty(SMTP_HOST_KEY, smtpServer);
    int smtpPort = config.getSmtpPort();
    props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort));

    // ???????
    Session session = null;
    if (authenticator_ == null) {
        // ?????
        session = Session.getDefaultInstance(props);
    } else {
        // ???
        props.setProperty(SMTP_AUTH_KEY, "true");
        session = Session.getDefaultInstance(props, authenticator_);
    }

    // MIME??
    MimeMessage message = new MimeMessage(session);

    // ??
    // :
    Date date = new Date();
    String encoding = this.config_.getSmtpEncoding();
    message.setHeader("X-Mailer", X_MAILER);
    message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\"");
    message.setSentDate(date);

    // :from
    String from = this.config_.getSmtpFrom();
    InternetAddress fromAddr = new InternetAddress(from);
    message.setFrom(fromAddr);

    // :to
    String[] recipients = this.config_.getSmtpTo().split(",");
    for (String toStr : recipients) {
        InternetAddress toAddr = new InternetAddress(toStr);
        message.addRecipient(Message.RecipientType.TO, toAddr);
    }

    // :body, subject
    String subject;
    String body;
    subject = createSubject(entry, date);
    try {
        body = createBody(entry, date);
    } catch (IOException ex) {
        LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, "");
        body = createDefaultBody(entry, date);
    }

    message.setSubject(subject, encoding);
    message.setText(body, encoding);

    return message;
}

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;//from   w w  w  .ja v a2s. com
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Sends an email in the correspondent type.
 *//*from w ww  . j ava  2  s  . co  m*/
public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject,
        String body_text, String body_html, int mailtype, String charset) {
    try {
        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("system.mail.host", getSmtpMailRelayHostname());
        Session session = Session.getDefaultInstance(props, null);
        // session.setDebug(debug);

        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from_adr));
        msg.setSubject(subject, charset);
        msg.setSentDate(new Date());

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.CC, ccAddresses);
        }

        switch (mailtype) {
        case 0:
            msg.setText(body_text, charset);
            break;

        case 1:
            Multipart mp = new MimeMultipart("alternative");
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setText(body_text, charset);
            mp.addBodyPart(mbp);
            mbp = new MimeBodyPart();
            mbp.setContent(body_html, "text/html; charset=" + charset);
            mp.addBodyPart(mbp);
            msg.setContent(mp);
            break;
        }

        Transport.send(msg);
    } catch (Exception e) {
        logger.error("sendEmail: " + e);
        logger.error(AgnUtils.getStackTrace(e));
        return false;
    }
    return true;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Sets the content for a message. Also attaches files to the message.
 * @throws MessagingException//ww w .  j a  v  a  2s.  c  om
 */
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg, String contentType,
        String charset, String multipartSubtype) throws MessagingException {
    ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
    if (attachments != null && attachments.size() > 0) {
        // Add attachments to messages
        for (Attachment attachment : attachments) {
            // attach the file to the message
            embeddedAttachments.add(createAttachmentPart(attachment));
        }
    }

    // if no direct attachments, keep the message simple and add the content as text.
    if (embeddedAttachments.size() == 0) {
        // if no contentType specified, go with text/plain
        if (contentType == null)
            msg.setText(content, charset);
        else
            msg.setContent(content, contentType);
    }
    // the multipart was constructed (ie. attachments available), use it as the message content
    else {
        // create a multipart container
        Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype)
                : new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        if (contentType == null)
            msgBodyPart.setText(content, charset);
        else
            msgBodyPart.setContent(content, contentType);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (MimeBodyPart attachPart : embeddedAttachments) {
            multipart.addBodyPart(attachPart);
        }

        // set the multipart container as the content of the message
        msg.setContent(multipart);
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body,
        List<DBMailAttachment> attachments, MailerResult result) {

    try {/*  w w  w .  ja v  a 2  s . c om*/
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        msg.setFrom(from);
        msg.setSubject(subject, "utf-8");

        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart();
            // 1) add body part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
            // 2) add attachments
            for (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                messageBodyPart = new MimeBodyPart();

                VFSLeaf data = getAttachmentDatas(attachment);
                DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            msg.setText(body, "utf-8");
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (MessagingException e) {
        logError("", e);
        return null;
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject,
        String body, List<File> attachments, MailerResult result) {

    try {/*from www  . jav  a 2s . c om*/
        //   see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection.
        // following doesn't work correctly, therefore add bounce-address in message already
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"),
                WebappHelper.getMailConfig("mailFromName"));
        msg.setFrom(viewableFrom);
        msg.setSubject(subject, "utf-8");
        // reply to can only be an address without name (at least for postfix!), see FXOLAT-312
        msg.setReplyTo(new Address[] { convertedFrom });

        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }

        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }

        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }

            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logError("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    }
}