Example usage for javax.mail.internet MimeMultipart addBodyPart

List of usage examples for javax.mail.internet MimeMultipart addBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart addBodyPart.

Prototype

@Override
public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }/*from   ww w.j a  v a 2 s  .co  m*/

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(getPlainTextContent(), "text/plain");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(getHtmlContent(), "text/html");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void setMimeMessageContent(SendingMessage sendingMessage, MimeMultipart content,
        MimeMultipart textPart) throws MessagingException {
    MimeBodyPart textBodyPart = new MimeBodyPart();
    MimeBodyPart contentBodyPart = new MimeBodyPart();
    String bodyContentType = getContentBodyType(sendingMessage);

    contentBodyPart.setContent(sendingMessage.getContentText(), bodyContentType);
    textPart.addBodyPart(contentBodyPart);
    textBodyPart.setContent(textPart);//from   w w w .  j  a  v a  2  s  .c  om
    content.addBodyPart(textBodyPart);
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }// w w w .j av a2s .  com

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/*from   www  .  j a v  a  2s. c  o m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.adaptris.mail.MailSenderImp.java

private void addEmailBody(MimeMultipart multipart) throws MailException {
    try {//from  w  w  w  . j av  a 2  s.  co m
        if (emailBody != null) {
            MimeBodyPart part = create(emailBody, new InternetHeaders(), encoding);
            part.setHeader(Mail.CONTENT_TYPE, bodyContentType);
            multipart.addBodyPart(part);
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected MimeMessage createMimeMessage(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = mailSender.createMimeMessage();
    assignRecipient(sendingMessage, msg);
    msg.setSubject(sendingMessage.getCaption(), StandardCharsets.UTF_8.name());
    msg.setSentDate(timeSource.currentTimestamp());

    assignFromAddress(sendingMessage, msg);
    addHeaders(sendingMessage, msg);//from   ww w  .  ja v  a2  s .c o  m

    MimeMultipart content = new MimeMultipart("mixed");
    MimeMultipart textPart = new MimeMultipart("related");

    setMimeMessageContent(sendingMessage, content, textPart);

    for (SendingAttachment attachment : sendingMessage.getAttachments()) {
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);

        if (attachment.getContentId() == null) {
            content.addBodyPart(attachmentPart);
        } else
            textPart.addBodyPart(attachmentPart);
    }

    msg.setContent(content);
    msg.saveChanges();
    return msg;
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

/**
 * Send email with Amazon Simple Email Service.
 * <p/>//from  ww  w  . j a  v  a  2s.  c  o m
 * 
 * Please note that the sender (ie 'from') must be a verified address (see
 * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)}
 * ).
 * <p/>
 * 
 * Please note that the sender is a CC of the meail to ease support.
 * <p/>
 * 
 * @param subject
 * @param body
 * @param from
 * @param toAddresses
 * @throws MessagingException
 * @throws AddressException
 */
public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair,
        java.security.KeyPair x509KeyPair, X509Certificate x509Certificate,
        SigningCertificate signingCertificate, String from, String toAddress) {

    try {
        Session s = Session.getInstance(new Properties(), null);
        MimeMessage msg = new MimeMessage(s);

        msg.setFrom(new InternetAddress(from));
        msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
        msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from));

        msg.setSubject(subject);

        MimeMultipart mimeMultiPart = new MimeMultipart();
        msg.setContent(mimeMultiPart);

        // body
        BodyPart plainTextBodyPart = new MimeBodyPart();
        mimeMultiPart.addBodyPart(plainTextBodyPart);
        plainTextBodyPart.setContent(body, "text/plain");

        // aws-credentials.txt / accessKey
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            StringWriter awsCredentialsStringWriter = new StringWriter();
            PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter);
            awsCredentials
                    .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials");
            awsCredentials.println("#" + new DateTime());
            awsCredentials.println();
            awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey");
            awsCredentials.println("accessKey=" + accessKey.getAccessKeyId());
            awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey());
            awsCredentials.println();
            awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey");
            awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId());
            awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey());

            awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain");
            mimeMultiPart.addBodyPart(awsCredentialsBodyPart);
        }
        // private ssh key
        {
            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt");
            keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream");
            mimeMultiPart.addBodyPart(keyPairBodyPart);
        }

        // x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart);
        }
        // x509 private key
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509CertificatePem = Pems.pem(x509Certificate);
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509CertificateBodyPart);
        }
        // Convert to raw message
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);

        RawMessage rawMessage = new RawMessage();
        rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes()));

        ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.adaptris.util.text.mime.MultiPartOutput.java

private void writeViaTempfile(OutputStream out, File tempFile) throws MessagingException, IOException {
    try (FileOutputStream fileOut = new FileOutputStream(tempFile);
            CountingOutputStream counter = new CountingOutputStream(fileOut)) {
        MimeMultipart multipart = new MimeMultipart();
        mimeHeader.setHeader(HEADER_CONTENT_TYPE, multipart.getContentType());
        // Write the part out to the stream first.
        for (KeyedBodyPart kbp : parts) {
            multipart.addBodyPart(kbp.getData());
        }// w w w.  jav a2  s .  c  om
        multipart.writeTo(counter);
        counter.flush();
        mimeHeader.setHeader(HEADER_CONTENT_LENGTH, String.valueOf(counter.count()));
    }
    writeHeaders(mimeHeader, out);
    try (InputStream in = new FileInputStream(tempFile)) {
        IOUtils.copy(in, out);
    }
}

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

/**
 * Render a message in the context of a particular subscriber
 * and subscription.//from   www.j a  v a 2  s . c om
 */
@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:com.adaptris.util.text.mime.MultiPartOutput.java

private void inMemoryWrite(OutputStream out) throws MessagingException, IOException {
    MimeMultipart multipart = new MimeMultipart();
    ByteArrayOutputStream partOut = new ByteArrayOutputStream();
    mimeHeader.setHeader(HEADER_CONTENT_TYPE, multipart.getContentType());
    // Write the part out to the stream first.
    for (KeyedBodyPart kbp : parts) {
        multipart.addBodyPart(kbp.getData());
    }/*www  .ja  v  a  2 s .c o m*/
    multipart.writeTo(partOut);
    mimeHeader.setHeader(HEADER_CONTENT_LENGTH, String.valueOf(partOut.size()));
    writeHeaders(mimeHeader, out);
    out.write(partOut.toByteArray());
}