Java Code Examples for javax.mail.internet.MimeMultipart#addBodyPart()

The following examples show how to use javax.mail.internet.MimeMultipart#addBodyPart() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the given plain text and HTML text as alternatives, offering
 * both options to the email client. Requires multipart mode.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param plainText the plain text for the message
 * @param htmlText the HTML text for the message
 * @throws MessagingException in case of errors
 */
public void setText(String plainText, String htmlText) throws MessagingException {
	Assert.notNull(plainText, "Plain text must not be null");
	Assert.notNull(htmlText, "HTML text must not be null");

	MimeMultipart messageBody = new MimeMultipart(MULTIPART_SUBTYPE_ALTERNATIVE);
	getMainPart().setContent(messageBody, CONTENT_TYPE_ALTERNATIVE);

	// Create the plain text part of the message.
	MimeBodyPart plainTextPart = new MimeBodyPart();
	setPlainTextToMimePart(plainTextPart, plainText);
	messageBody.addBodyPart(plainTextPart);

	// Create the HTML text part of the message.
	MimeBodyPart htmlTextPart = new MimeBodyPart();
	setHtmlTextToMimePart(htmlTextPart, htmlText);
	messageBody.addBodyPart(htmlTextPart);
}
 
Example 2
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example 3
Source File: FileUploadsUtil.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private static MimeMultipart split(byte[] pattern, byte[] input, int sizeLimit) {

    MimeMultipart mmp = new MimeMultipart();
    int start = 0;
    int pos   = Bytes.indexOf(input, pattern);
    int size  = input.length;
    int entryCount = 0;
    ByteBuffer buffer = ByteBuffer.wrap(input);

    while(pos != -1 && start < size){

      int end = pos + pattern.length;
      if(entryCount != 0){
        //dont add the boundary itself - which is what you have in the first iteration
        buffer.position(start);

        //not a copy but points to the buffer
        //used for the indexOf functionality to keep checking
        //further on in the buffer - current pos -> end of buffer
        byte[] tmpBuffer = buffer.slice().array();

        //set limit - now that limit is set re-slice to only get the needed
        //area -
        buffer.limit(end);

        try {
          MimeBodyPart mbp = new MimeBodyPart(new InternetHeaders(), buffer.slice().array());
          mmp.addBodyPart(mbp);
        } catch (MessagingException e) {
          log.error(e.getMessage(), e);
        }
        pos = Bytes.indexOf(tmpBuffer, pattern);
      }
      entryCount++;
      start = end;
    }
    return mmp;
  }
 
Example 4
Source File: Postman.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * Listen for e-mail requests through CDI events and send the message
 *
 * @param mailMessage the message to send
 * @throws Exception if any problem occur in the process
 */
public void send(@Observes MailMessage mailMessage) throws Exception {

    // create the message
    final MimeMessage message = new MimeMessage(this.mailSession);

    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());

    message.setSentDate(new Date());

    final MimeMultipart multipart = new MimeMultipart();

    // message text
    final MimeBodyPart messagePart = new MimeBodyPart();

    messagePart.setText(mailMessage.getContent(), "UTF-8", "html");
    multipart.addBodyPart(messagePart);

    // attachments part
    mailMessage.getAttachments().forEach(file -> {
        try {
            final FileDataSource dataSource = new FileDataSource(file);
            final MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(dataSource));
            attachmentPart.setFileName(dataSource.getName());
            multipart.addBodyPart(attachmentPart);
        } catch (MessagingException ex) {
            throw new BusinessLogicException("error.email.cant-attach-file", ex, file.getName());
        }
    });

    message.setContent(multipart);

    // send
    Transport.send(message);
}
 
Example 5
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
protected MimeMessage getMultipartMessage() throws Exception {
    MimeMessage mmCreated = MimeMessageUtil.defaultMimeMessage();
    mmCreated.setSubject("test");
    mmCreated.addHeader("Date", "Tue, 16 Jan 2018 09:56:01 +0700 (ICT)");
    MimeMultipart mm = new MimeMultipart("alternative");
    mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test1\r\nContent-Type: text/plain; charset=Cp1252\r\n"
            .getBytes())), "first part òàù".getBytes()));
    mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test2\r\nContent-Type: text/plain; charset=Cp1252\r\nContent-Transfer-Encoding: quoted-printable\r\n"
            .getBytes())), "second part =E8=E8".getBytes()));
    mmCreated.setContent(mm);
    mmCreated.saveChanges();
    return mmCreated;
}
 
Example 6
Source File: MimePackage.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Add a multipart/alternative part to message body
 *
 * @param plainContent
 *            the content of the text/plain sub-part
 * @param htmlContent
 *            the content of the text/html sub-part
 * @param charset
 *            the character set for the part
 * @throws PackageException
 */
@PublicAtsApi
public void addAlternativePart(
                                String plainContent,
                                String htmlContent,
                                String charset ) throws PackageException {

    MimeMultipart alternativePart = new MimeMultipart("alternative");

    try {
        // create a new text/plain part
        MimeBodyPart plainPart = new MimeBodyPart();
        plainPart.setText(plainContent, charset, PART_TYPE_TEXT_PLAIN);
        plainPart.setDisposition(MimeBodyPart.INLINE);

        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setText(htmlContent, charset, PART_TYPE_TEXT_HTML);
        htmlPart.setDisposition(MimeBodyPart.INLINE);

        alternativePart.addBodyPart(plainPart, 0);
        alternativePart.addBodyPart(htmlPart, 1);

        MimeBodyPart mimePart = new MimeBodyPart();
        mimePart.setContent(alternativePart);

        addPart(mimePart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example 7
Source File: MailingService.java    From blog-tutorials with MIT License 5 votes vote down vote up
public void sendSimpleMail() {

    Message simpleMail = new MimeMessage(mailSession);

    try {
      simpleMail.setSubject("Hello World from Java EE!");
      simpleMail.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));

      MimeMultipart mailContent = new MimeMultipart();

      MimeBodyPart mailMessage = new MimeBodyPart();
      mailMessage.setContent("<p>Take a look at the <b>scecretMessage.txt</b> file</p>", "text/html; charset=utf-8");
      mailContent.addBodyPart(mailMessage);

      MimeBodyPart mailAttachment = new MimeBodyPart();
      DataSource source = new ByteArrayDataSource("This is a secret message".getBytes(), "text/plain");
      mailAttachment.setDataHandler(new DataHandler(source));
      mailAttachment.setFileName("secretMessage.txt");

      mailContent.addBodyPart(mailAttachment);
      simpleMail.setContent(mailContent);

      Transport.send(simpleMail);

      System.out.println("Message successfully send to: " + emailAddress);
    } catch (MessagingException e) {
      e.printStackTrace();
    }

  }
 
Example 8
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldBeDetected() throws Exception {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                        Joiner.on("\r\n").join(
                            "Final-Recipient: rfc822;[email protected]",
                            "Disposition: automatic-action/MDN-sent-automatically; displayed",
                            ""),
                            "message/disposition-notification;")
                    ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example 9
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
/**
 * 追加附件
 * @author hf-hf
 * @date 2018/12/27 16:53
 * @param attachments
 * @param wrapPart
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private void addAttachments(File[] attachments, MimeMultipart wrapPart)
        throws MessagingException, UnsupportedEncodingException {
    if (null != attachments && attachments.length > 0) {
        for (int i = 0; i < attachments.length; i++) {
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(attachments[i]));
            String fileName = dataHandler.getName();
            attachmentBodyPart.setDataHandler(dataHandler);
            // 显示指定文件名(防止文件名乱码)
            attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
            wrapPart.addBodyPart(attachmentBodyPart);
        }
    }
}
 
Example 10
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldDetectBigMDN() throws Exception {

    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
        new DataHandler(
            new ByteArrayDataSource(
                Joiner.on("\r\n").join(
                    "Final-Recipient: rfc822;[email protected]",
                    "Disposition: automatic-action/MDN-sent-automatically; displayed",
                    ""),
                "message/disposition-notification;")
        ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    BodyPart bigBody = MimeMessageBuilder.bodyPartBuilder() // ~3MB
        .data("12345678\r\n".repeat(300 * 1024))
        .build();
    multipart.addBodyPart(bigBody);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
        .name("mail")
        .sender(MailAddressFixture.ANY_AT_JAMES)
        .mimeMessage(message)
        .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example 11
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Determine the MimeMultipart objects to use, which will be used
 * to store attachments on the one hand and text(s) and inline elements
 * on the other hand.
 * <p>Texts and inline elements can either be stored in the root element
 * itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED) or in a nested element
 * rather than the root element directly (MULTIPART_MODE_MIXED_RELATED).
 * <p>By default, the root MimeMultipart element will be of type "mixed"
 * (MULTIPART_MODE_MIXED) or "related" (MULTIPART_MODE_RELATED).
 * The main multipart element will either be added as nested element of
 * type "related" (MULTIPART_MODE_MIXED_RELATED) or be identical to the root
 * element itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED).
 * @param mimeMessage the MimeMessage object to add the root MimeMultipart
 * object to
 * @param multipartMode the multipart mode, as passed into the constructor
 * (MIXED, RELATED, MIXED_RELATED, or NO)
 * @throws MessagingException if multipart creation failed
 * @see #setMimeMultiparts
 * @see #MULTIPART_MODE_NO
 * @see #MULTIPART_MODE_MIXED
 * @see #MULTIPART_MODE_RELATED
 * @see #MULTIPART_MODE_MIXED_RELATED
 */
protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException {
	switch (multipartMode) {
		case MULTIPART_MODE_NO:
			setMimeMultiparts(null, null);
			break;
		case MULTIPART_MODE_MIXED:
			MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
			mimeMessage.setContent(mixedMultipart);
			setMimeMultiparts(mixedMultipart, mixedMultipart);
			break;
		case MULTIPART_MODE_RELATED:
			MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
			mimeMessage.setContent(relatedMultipart);
			setMimeMultiparts(relatedMultipart, relatedMultipart);
			break;
		case MULTIPART_MODE_MIXED_RELATED:
			MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
			mimeMessage.setContent(rootMixedMultipart);
			MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
			MimeBodyPart relatedBodyPart = new MimeBodyPart();
			relatedBodyPart.setContent(nestedRelatedMultipart);
			rootMixedMultipart.addBodyPart(relatedBodyPart);
			setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart);
			break;
		default:
			throw new IllegalArgumentException("Only multipart modes MIXED_RELATED, RELATED and NO supported");
	}
}
 
Example 12
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
/**
 * 追加附件
 * @author hf-hf
 * @date 2018/12/27 16:53
 * @param attachments
 * @param wrapPart
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private void addAttachments(File[] attachments, MimeMultipart wrapPart)
        throws MessagingException, UnsupportedEncodingException {
    if (null != attachments && attachments.length > 0) {
        for (int i = 0; i < attachments.length; i++) {
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(attachments[i]));
            String fileName = dataHandler.getName();
            attachmentBodyPart.setDataHandler(dataHandler);
            // 显示指定文件名(防止文件名乱码)
            attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
            wrapPart.addBodyPart(attachmentBodyPart);
        }
    }
}
 
Example 13
Source File: HasAttachmentTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void multipartWithOneAttachmentShouldBeMatched() throws Exception {
    MimeMultipart mimeMultipart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setDisposition(MimeMessage.INLINE);
    mimeMultipart.addBodyPart(textPart);
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDisposition(MimeMessage.ATTACHMENT);
    mimeMultipart.addBodyPart(attachmentPart);
    mimeMessage.setContent(mimeMultipart);

    assertThat(testee.match(mail)).containsAll(mail.getRecipients());
}
 
Example 14
Source File: MessageToCoreToMessage.java    From james-project with Apache License 2.0 4 votes vote down vote up
protected MimeMultipart help() throws MessagingException {
    MimeMultipart multipart = new MimeMultipart();
    multipart.addBodyPart(toPart(helpProvider.getHelp()));
    return multipart;
}
 
Example 15
Source File: Mail4Customize.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean send(Message msg) {
    boolean isOk = true;
    Transport transport = null;
    try {
        LOG.info(String.format("Address: %s", msg.getAddress()));
        LOG.info(String.format("Subject: %s", msg.getSubject() + ENV));
        LOG.info(String.format("Contents: %s", msg.getContents()));
        LOG.info(String.format("Host: %s", msg.getHost()));
        LOG.info(String.format("Port: %s", msg.getPort()));
        LOG.info(String.format("User name: %s", msg.getUserName()));

        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", msg.getHost());

        Session session = Session.getInstance(props);
        // session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(msg.getFromAddress());
        message.setRecipients(javax.mail.Message.RecipientType.TO, msg.getAddress());
        message.setSubject(msg.getSubject());

        MimeMultipart mmp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent(msg.getContents(), "text/html;charset=UTF-8");

        mmp.addBodyPart(mbp);
        mmp.setSubType("mixed");

        message.setContent(mmp);
        message.setSentDate(new Date());

        transport = session.getTransport();
        transport.connect(msg.getHost(), msg.getPort(), msg.getUserName(), msg.getPassword());
        transport.sendMessage(message, message.getAllRecipients());

        LOG.error("mail for customize send email success.");
    } catch (Exception e) {
        isOk = false;
        LOG.error("mail for customize send email fail.", e);
    } finally {
        close(transport);
    }
    return isOk;
}
 
Example 16
Source File: SendMessageAttachment.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void send(byte[] attachment) throws AddressException, MessagingException, IOException {

        Session session = Session.getDefaultInstance(new Properties());

        // Create a new MimeMessage object
        MimeMessage message = new MimeMessage(session);

        // Add subject, from and to lines
        message.setSubject(SUBJECT, "UTF-8");
        message.setFrom(new InternetAddress(SENDER));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));

        // Create a multipart/alternative child container
        MimeMultipart msgBody = new MimeMultipart("alternative");

        // Create a wrapper for the HTML and text parts
        MimeBodyPart wrap = new MimeBodyPart();

        // Define the text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");

        // Define the HTML part
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");

        // Add the text and HTML parts to the child container
        msgBody.addBodyPart(textPart);
        msgBody.addBodyPart(htmlPart);

        // Add the child container to the wrapper object
        wrap.setContent(msgBody);

        // Create a multipart/mixed parent container
        MimeMultipart msg = new MimeMultipart("mixed");

        // Add the parent container to the message
        message.setContent(msg);

        // Add the multipart/alternative part to the message
        msg.addBodyPart(wrap);

        // Define the attachment
        MimeBodyPart att = new MimeBodyPart();
        DataSource fds = new ByteArrayDataSource(attachment, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        att.setDataHandler(new DataHandler(fds));

        // Set the attachment name
        String reportName = "WorkReport.xls";
        att.setFileName(reportName);

        // Add the attachment to the message
        msg.addBodyPart(att);

        try {
            System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

            Region region = Region.US_WEST_2;

            SesClient client = SesClient.builder().region(region).build();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            message.writeTo(outputStream);

            ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

            byte[] arr = new byte[buf.remaining()];
            buf.get(arr);

            SdkBytes data = SdkBytes.fromByteArray(arr);

            RawMessage rawMessage = RawMessage.builder()
                    .data(data)
                    .build();

            SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                    .rawMessage(rawMessage)
                    .build();

            client.sendRawEmail(rawEmailRequest);

        } catch (SdkException e) {
            e.getStackTrace();
        }
        // snippet-end:[ses.java2.sendmessageattachment.main]
    }
 
Example 17
Source File: EmailFormatterOutboud.java    From matrix-appservice-email with GNU Affero General Public License v3.0 4 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, List<_BridgeMessageContent> contents, boolean allowReply) throws MessagingException, IOException {
    MimeMultipart body = new MimeMultipart();
    body.setSubType("alternative");

    for (_BridgeMessageContent content : contents) {
        MimeMultipart contentBody = new MimeMultipart();
        contentBody.setSubType("related");

        Optional<_EmailTemplateContent> contentTemplateOpt = template.getContent(content.getMime());
        if (!contentTemplateOpt.isPresent()) {
            continue;
        }

        _EmailTemplateContent contentTemplate = contentTemplateOpt.get();
        contentBody.addBodyPart(makeBodyPart(data, contentTemplate, content));

        if (contentTemplate.getContent().contains(EmailTemplateToken.SenderAvatar.getToken()) &&
                data.getSenderAvatar() != null && data.getSenderAvatar().isValid()) {
            log.info("Adding avatar for sender");

            MimeBodyPart avatarBp = new MimeBodyPart();
            _MatrixContent avatar = data.getSenderAvatar();
            String filename = avatar.getFilename()
                    .map(f -> f.replace("image/", "").replace("\"", ""))
                    .filter(StringUtils::isNotBlank)
                    .orElseGet(() -> "unknown." + avatar.getType());

            avatarBp.setContent(avatar.getData(), avatar.getType());
            avatarBp.setContentID("<" + senderAvatarId + ">");
            avatarBp.setDisposition("inline; filename=\"" + filename + "\"; size=" + avatar.getData().length + ";");

            contentBody.addBodyPart(avatarBp);
        }

        MimeBodyPart part = new MimeBodyPart();
        part.setContent(contentBody);

        body.addBodyPart(part);
    }

    return makeEmail(data, template, body, allowReply);
}
 
Example 18
Source File: WhiteListManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
        MailAddress notifier = getMailetContext().getPostmaster();

        MailAddress senderMailAddress = mail.getMaybeSender().get();

        MimeMessage message = mail.getMessage();
        // Create the reply message
        MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

        // Create the list of recipients in the Address[] format
        InternetAddress[] rcptAddr = new InternetAddress[1];
        rcptAddr[0] = senderMailAddress.toInternetAddress();
        reply.setRecipients(Message.RecipientType.TO, rcptAddr);

        // Set the sender...
        reply.setFrom(notifier.toInternetAddress());

        // Create the message body
        MimeMultipart multipart = new MimeMultipart();
        // Add message as the first mime body part
        MimeBodyPart part = new MimeBodyPart();
        part.setContent(stringContent, "text/plain");
        part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
        multipart.addBodyPart(part);

        reply.setContent(multipart);
        reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

        // Create the list of recipients in our MailAddress format
        Set<MailAddress> recipients = new HashSet<>();
        recipients.add(senderMailAddress);

        // Set additional headers
        if (reply.getHeader(RFC2822Headers.DATE) == null) {
            reply.setHeader(RFC2822Headers.DATE, DateFormats.RFC822_DATE_FORMAT.format(LocalDateTime.now()));
        }
        String subject = message.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (subject.indexOf("Re:") == 0) {
            reply.setSubject(subject);
        } else {
            reply.setSubject("Re:" + subject);
        }
        reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

        // Send it off...
        getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
        LOGGER.error("Exception found sending reply", e);
    }
}
 
Example 19
Source File: SendMessage.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void send(SesClient client,
                        String sender,
                        String recipient,
                        String subject,
                        String bodyText,
                        String bodyHTML
) throws AddressException, MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());

    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Add subject, from and to lines.
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

    // Create a multipart/alternative child container.
    MimeMultipart msgBody = new MimeMultipart("alternative");

    // Create a wrapper for the HTML and text parts.
    MimeBodyPart wrap = new MimeBodyPart();

    // Define the text part.
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");

    // Define the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");

    // Add the text and HTML parts to the child container.
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);

    // Add the child container to the wrapper object.
    wrap.setContent(msgBody);

    // Create a multipart/mixed parent container.
    MimeMultipart msg = new MimeMultipart("mixed");

    // Add the parent container to the message.
    message.setContent(msg);

    // Add the multipart/alternative part to the message.
    msg.addBodyPart(wrap);

    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);

        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);

        SdkBytes data = SdkBytes.fromByteArray(arr);

        RawMessage rawMessage = RawMessage.builder()
                .data(data)
                .build();

        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                .rawMessage(rawMessage)
                .build();

        client.sendRawEmail(rawEmailRequest);

    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }


}
 
Example 20
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 4 votes vote down vote up
/**
 * 发送邮件(负载均衡)
 *
 * @param key           负载均衡key
 * @param to            收件人,多个收件人用 {@code ;} 分隔
 * @param cc            抄送人,多个抄送人用 {@code ;} 分隔
 * @param bcc           密送人,多个密送人用 {@code ;} 分隔
 * @param subject       主题
 * @param content       内容,可引用内嵌图片,引用方式:{@code <img src="cid:内嵌图片文件名" />}
 * @param images        内嵌图片
 * @param attachments   附件
 * @return              如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
 */
public boolean sendByLoadBalance(String key, String to, String cc,
                                 String bcc, String subject, String content,
                                 File[] images, File[] attachments){
    log.info("loadBalanceKey={}", key);
    Properties properties = MailManager.getProperties(key);
    log.info("properties={}", properties);
    Session session = MailManager.getSession(key);
    MimeMessage message = new MimeMessage(session);
    String username = properties.getProperty("mail.username");
    ThreadLocalUtils.put(Constants.CURRENT_MAIL_FROM, username);
    try {
        message.setFrom(new InternetAddress(username));
        addRecipients(message, Message.RecipientType.TO, to);
        if (cc != null) {
            addRecipients(message, Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            addRecipients(message, Message.RecipientType.BCC, bcc);
        }
        message.setSubject(subject, CHART_SET_UTF8);
        // 最外层部分
        MimeMultipart wrapPart = new MimeMultipart("mixed");
        MimeMultipart htmlWithImageMultipart = new MimeMultipart("related");
        // 文本部分
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(content, CONTENT_TYPE_HTML);
        htmlWithImageMultipart.addBodyPart(htmlPart);
        // 内嵌图片部分
        addImages(images, htmlWithImageMultipart);
        MimeBodyPart htmlWithImageBodyPart = new MimeBodyPart();
        htmlWithImageBodyPart.setContent(htmlWithImageMultipart);
        wrapPart.addBodyPart(htmlWithImageBodyPart);
        // 附件部分
        addAttachments(attachments, wrapPart);
        message.setContent(wrapPart);
        Transport.send(message);
        return true;
    } catch (Exception e) {
        log.error("sendByLoadBalance error!", e.getMessage(),
                "loadBalanceKey={}, properties={}, to={}, cc={}, "
                + "bcc={}, subject={}, content={}, images={}, attachments={}",
                key, properties, to, cc,
                bcc, subject, content, images, attachments, e);
    }
    return false;
}