Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:com.anteam.alert.email.service.EmailAntlert.java

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?/*ww w. java  2s . c o m*/
    mimeMsg = new javax.mail.internet.MimeMessage(mailSession);

    try {
        // ?
        mimeMsg.setFrom(sender);
        // 
        mimeMsg.setRecipients(RecipientType.TO, receivers);
        // 
        mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET);

        // 
        MimeBodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBody);
        mimeMsg.setContent(multipart);

        // ??
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        // ??
        Transport.send(mimeMsg);
    } catch (MessagingException e) {
        logger.error("???", e);
        return false;
    }
    return true;
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header./*from   ww  w .jav a  2s. c  om*/
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}

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

/**
 * Send email with Amazon Simple Email Service.
 * <p/>/*from  w w  w.  ja v  a  2 s  . 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.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {//from   w  w  w  .j a  va  2 s.co m
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        InternetAddress addressFrom = new InternetAddress(emailFrom);
        message.setFrom(addressFrom);

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

        DataSource source = new FileDataSource(attachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(attachment.getName());
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void createMultipartAlternativeMessage(MimeMessage mimeMessage, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    MimeMultipart multipartAlternative = new MimeMultipart("alternative");
    mimeMessage.setContent(multipartAlternative);

    MimeBodyPart plainText = new MimeBodyPart();
    plainText.setText(getAlternativeBody(configuration, exchange), determineCharSet(configuration, exchange));
    // remove the header with the alternative mail now that we got it
    // otherwise it might end up twice in the mail reader
    exchange.getIn().removeHeader(configuration.getAlternativeBodyHeader());
    multipartAlternative.addBodyPart(plainText);

    // if there are no attachments, add the body to the same mulitpart message
    if (!exchange.getIn().hasAttachments()) {
        addBodyToMultipart(configuration, multipartAlternative, exchange);
    } else {/*from w  w  w .  ja va  2s.  co m*/
        // if there are attachments, but they aren't set to be inline, add them to
        // treat them as normal. It will append a multipart-mixed with the attachments and the body text
        if (!configuration.isUseInlineAttachments()) {
            BodyPart mixedAttachments = new MimeBodyPart();
            mixedAttachments.setContent(createMixedMultipartAttachments(configuration, exchange));
            multipartAlternative.addBodyPart(mixedAttachments);
        } else {
            // if the attachments are set to be inline, attach them as inline attachments
            MimeMultipart multipartRelated = new MimeMultipart("related");
            BodyPart related = new MimeBodyPart();

            related.setContent(multipartRelated);
            multipartAlternative.addBodyPart(related);

            addBodyToMultipart(configuration, multipartRelated, exchange);

            addAttachmentsToMultipart(multipartRelated, Part.INLINE, exchange);
        }
    }
}

From source file:nl.surfnet.coin.teams.control.AddMemberController.java

/**
 * Sends an email based on the {@link Invitation}
 *
 * @param invitation {@link Invitation} that contains the necessary data
 * @param subject    of the email/*from  w w w.j  av  a2 s  .com*/
 * @param inviter    {@link Person} who sends the invitation
 * @param locale     {@link Locale} for the mail
 */
protected void sendInvitationByMail(final Invitation invitation, final String subject, final Person inviter,
        final Locale locale) {

    final String html = composeInvitationMailMessage(invitation, inviter, locale, "html");
    final String plainText = composeInvitationMailMessage(invitation, inviter, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(invitation.getEmail()));
            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:com.zimbra.cs.service.FeedManager.java

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr,
        Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext();) {
            if (it.next().getLocation() == null) {
                it.remove();/*from w ww  .  j  a v a  2s  .c o m*/
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();

    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }

    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);

        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }

        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress)
        throws MessagingException {

    MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart();

    // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview)
    MimeMultipart cover = new MimeMultipart("alternative");
    htmlAndPlainTextAlternativeBody.setContent(cover);
    BodyPart textHtmlBodyPart = new MimeBodyPart();
    String textHtmlBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".html.ftl");
    textHtmlBodyPart.setContent(textHtmlBody, "text/html");
    cover.addBodyPart(textHtmlBodyPart);

    BodyPart textPlainBodyPart = new MimeBodyPart();
    cover.addBodyPart(textPlainBodyPart);
    String textPlainBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".txt.ftl");
    textPlainBodyPart.setContent(textPlainBody, "text/plain");

    MimeMultipart content = new MimeMultipart("related");
    content.addBodyPart(htmlAndPlainTextAlternativeBody);

    // ATTACHMENTS
    for (BodyPart bodyPart : attachments) {
        content.addBodyPart(bodyPart);//  w w  w .  ja  va 2  s  . c o m
    }

    MimeMessage msg = new MimeMessage(mailSession);

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

    String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials";

    msg.setSubject(subject);
    msg.setContent(content);

    mailTransport.sendMessage(msg, msg.getAllRecipients());
}

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

/**
 * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set
 * @return/*from www  .  ja v  a2 s .c o  m*/
 * @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;
}