Java Code Examples for javax.mail.internet.MimeMessage#writeTo()
The following examples show how to use
javax.mail.internet.MimeMessage#writeTo() .
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: TestExtractEmailHeaders.java From nifi with Apache License 2.0 | 6 votes |
/** * NIFI-4326 adds a new feature to disable strict address parsing for * mailbox list header fields. This is a test case that asserts that * strict address parsing fails (when set to "strict=true") for malformed * addresses. */ @Test public void testStrictParsingFailsForInvalidAddresses() throws Exception { final TestRunner runner = TestRunners.newTestRunner(new ExtractEmailHeaders()); runner.setProperty(ExtractEmailHeaders.STRICT_PARSING, "true"); MimeMessage simpleEmailMimeMessage = attachmentGenerator.SimpleEmailMimeMessage(); simpleEmailMimeMessage.setHeader("From", "<bad_email>"); simpleEmailMimeMessage.setHeader("To", "<>, Joe, <invalid>"); ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); try { simpleEmailMimeMessage.writeTo(messageBytes); } catch (IOException | MessagingException e) { e.printStackTrace(); } runner.enqueue(messageBytes.toByteArray()); runner.run(); runner.assertTransferCount(ExtractEmailHeaders.REL_SUCCESS, 0); runner.assertTransferCount(ExtractEmailHeaders.REL_FAILURE, 1); }
Example 2
Source File: MDNTest.java From james-project with Apache License 2.0 | 6 votes |
@Test public void asMimeMessageShouldComportExplanationPartAndReportPart() throws Exception { MimeMessage mimeMessage = MDN.builder() .humanReadableText("Explanation") .report(MINIMAL_REPORT) .build() .asMimeMessage(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); mimeMessage.writeTo(byteArrayOutputStream); assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) .contains( "Content-Type: text/plain; charset=UTF-8\r\n" + "Content-Transfer-Encoding: 7bit\r\n" + "Content-Disposition: inline\r\n" + "\r\n" + "Explanation") .contains( "Content-Type: message/disposition-notification\r\n" + "Content-Transfer-Encoding: 7bit\r\n" + "\r\n" + "Final-Recipient: rfc822; [email protected]\r\n" + "Disposition: automatic-action/MDN-sent-automatically;deleted"); }
Example 3
Source File: GoogleMailIntegrationTest.java From wildfly-camel with Apache License 2.0 | 6 votes |
private static Message createMessage(ProducerTemplate template, String subject) throws MessagingException, IOException { Profile profile = template.requestBody("google-mail://users/getProfile?inBody=userId", CURRENT_USERID, Profile.class); Session session = Session.getDefaultInstance(new Properties(), null); MimeMessage mm = new MimeMessage(session); mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress()); mm.setSubject(subject); mm.setContent("Camel rocks!\n" // + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" // + "user: " + System.getProperty("user.name"), "text/plain"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mm.writeTo(baos); String encodedEmail = Base64.getUrlEncoder().encodeToString(baos.toByteArray()); Message message = new Message(); message.setRaw(encodedEmail); return message; }
Example 4
Source File: MimeMessageCopyOnWriteProxyTest.java From james-project with Apache License 2.0 | 6 votes |
/** * This test throw a NullPointerException when the original message was * created by a MimeMessageInputStreamSource. */ @Test void testMessageCloningViaCoW3() throws Exception { MimeMessage mmorig = getSimpleMessage(); MimeMessage mm = new MimeMessageCopyOnWriteProxy(mmorig); LifecycleUtil.dispose(mmorig); mmorig = null; System.gc(); Thread.sleep(200); try { mm.writeTo(System.out); } catch (Exception e) { e.printStackTrace(); fail("Exception while writing the message to output"); } LifecycleUtil.dispose(mm); }
Example 5
Source File: GoogleMailResource.java From camel-quarkus with Apache License 2.0 | 6 votes |
private Message createMessage(String body) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties(), null); Profile profile = producerTemplate.requestBody("google-mail://users/getProfile?inBody=userId", USER_ID, Profile.class); MimeMessage mm = new MimeMessage(session); mm.addRecipients(TO, profile.getEmailAddress()); mm.setSubject(EMAIL_SUBJECT); mm.setContent(body, "text/plain"); Message message = new Message(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { mm.writeTo(baos); message.setRaw(Base64.getUrlEncoder().encodeToString(baos.toByteArray())); } return message; }
Example 6
Source File: TestImap.java From davmail with GNU General Public License v2.0 | 5 votes |
public void testAppendWithKeywordFlags() throws IOException, MessagingException { resetTestFolder(); MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("to", "testto <" + Settings.getProperty("davmail.to") + ">"); mimeMessage.addHeader("cc", "testcc <" + Settings.getProperty("davmail.to") + ">"); mimeMessage.setText("Test message "); mimeMessage.setSubject("Test subject "); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); byte[] content = baos.toByteArray(); writeLine(". APPEND testfolder (\\Seen some_tag \\Draft $Label4) {" + content.length + '}'); assertEquals("+ send literal data", readLine()); writeLine(new String(content)); assertEquals(". OK APPEND completed", readFullAnswer(".")); writeLine(". NOOP"); assertEquals(". OK NOOP completed", readFullAnswer(".")); // fetch message uid writeLine(". UID FETCH 1:* (FLAGS)"); String messageLine = readLine(); int uidIndex = messageLine.indexOf("UID ") + 4; messageUid = messageLine.substring(uidIndex, messageLine.indexOf(' ', uidIndex)); assertEquals(". OK UID FETCH completed", readFullAnswer(".")); assertNotNull(messageUid); writeLine(". UID FETCH " + messageUid + " (FLAGS)"); assertEquals("* 1 FETCH (UID " + messageUid + " FLAGS (\\Seen \\Draft $label4 some_tag))", readLine()); assertEquals(". OK UID FETCH completed", readFullAnswer(".")); }
Example 7
Source File: EwsExchangeSession.java From davmail with GNU General Public License v2.0 | 5 votes |
@Override public void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException { String itemClass = null; if (mimeMessage.getContentType().startsWith("multipart/report")) { itemClass = "REPORT.IPM.Note.IPNRN"; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { mimeMessage.writeTo(baos); } catch (MessagingException e) { throw new IOException(e.getMessage()); } sendMessage(itemClass, baos.toByteArray()); }
Example 8
Source File: TestImapErrorHandling.java From davmail with GNU General Public License v2.0 | 5 votes |
public void testFetchBigMessage() throws IOException, MessagingException { testCreateFolder(); // create 10MB message MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("to", Settings.getProperty("davmail.to")); mimeMessage.addHeader("bcc", Settings.getProperty("davmail.bcc")); Random random = new Random(); StringBuilder randomText = new StringBuilder(); for (int i = 0; i < 10 * 1024 * 1024; i++) { randomText.append((char) ('a' + random.nextInt(26))); } mimeMessage.setText(randomText.toString()); mimeMessage.setSubject("Big subject"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); byte[] content = baos.toByteArray(); long start = System.currentTimeMillis(); writeLine(". APPEND testfolder (\\Seen \\Draft) {" + content.length + '}'); assertEquals("+ send literal data", readLine()); writeLine(new String(content)); assertEquals(". OK APPEND completed", readFullAnswer(".")); System.out.println("Create time: " + (System.currentTimeMillis() - start) + " ms"); writeLine(". NOOP"); assertEquals(". OK NOOP completed", readFullAnswer(".")); start = System.currentTimeMillis(); writeLine(". UID FETCH 1:* (RFC822.SIZE BODY.TEXT)"); readFullAnswer("."); System.out.println("Fetch time: " + (System.currentTimeMillis() - start) + " ms"); }
Example 9
Source File: DumpSystemErr.java From james-project with Apache License 2.0 | 5 votes |
/** * Writes the message to System.err . * * @param mail the mail to process * * @throws MessagingException if an error occurs while writing the message */ @Override public void service(Mail mail) throws MessagingException { try { MimeMessage message = mail.getMessage(); message.writeTo(System.err); } catch (IOException ioe) { LOGGER.error("error printing message", ioe); } }
Example 10
Source File: AbstractImapTestCase.java From davmail with GNU General Public License v2.0 | 5 votes |
public void appendHundredMessages() throws IOException, MessagingException { for (int i = 0; i < 100; i++) { MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("to", "testto <" + Settings.getProperty("davmail.to") + ">"); mimeMessage.setText("Test message " + i); mimeMessage.setSubject("Test subject " + i); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); byte[] content = baos.toByteArray(); writeLine(". APPEND testfolder (\\Seen \\Draft) {" + content.length + '}'); assertEquals("+ send literal data", readLine()); writeLine(new String(content)); assertEquals(". OK APPEND completed", readFullAnswer(".")); } }
Example 11
Source File: TestExchange2003ActiveSyncBug.java From davmail with GNU General Public License v2.0 | 5 votes |
public byte[] buildContent() throws MessagingException, IOException { MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("to", "testto <" + Settings.getProperty("davmail.to") + ">"); mimeMessage.addHeader("cc", "testcc <" + Settings.getProperty("davmail.to") + ">"); mimeMessage.setText("Test message "); mimeMessage.setSubject("Test subject "); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); byte[] content = baos.toByteArray(); return content; }
Example 12
Source File: ExtractMDNOriginalJMAPMessageId.java From james-project with Apache License 2.0 | 5 votes |
private Optional<Message> parseMessage(MimeMessage mimeMessage) { LOGGER.debug("Parsing message"); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); mimeMessage.writeTo(os); Message message = new DefaultMessageBuilder().parseMessage(new ByteArrayInputStream(os.toByteArray())); return Optional.of(message); } catch (IOException | MessagingException e) { LOGGER.error("unable to parse message", e); return Optional.empty(); } }
Example 13
Source File: TestExtractEmailHeaders.java From nifi with Apache License 2.0 | 5 votes |
/** * Test case added for NIFI-4326 for a potential NPE bug * if the email message contains no recipient header fields, ie, * TO, CC, BCC. */ @Test public void testValidEmailWithNoRecipients() throws Exception { final TestRunner runner = TestRunners.newTestRunner(new ExtractEmailHeaders()); runner.setProperty(ExtractEmailHeaders.CAPTURED_HEADERS, "MIME-Version"); MimeMessage simpleEmailMimeMessage = attachmentGenerator.SimpleEmailMimeMessage(); simpleEmailMimeMessage.removeHeader("To"); simpleEmailMimeMessage.removeHeader("Cc"); simpleEmailMimeMessage.removeHeader("Bcc"); ByteArrayOutputStream messageBytes = new ByteArrayOutputStream(); try { simpleEmailMimeMessage.writeTo(messageBytes); } catch (IOException | MessagingException e) { e.printStackTrace(); } runner.enqueue(messageBytes.toByteArray()); runner.run(); runner.assertTransferCount(ExtractEmailHeaders.REL_SUCCESS, 1); runner.assertTransferCount(ExtractEmailHeaders.REL_FAILURE, 0); runner.assertQueueEmpty(); final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(ExtractEmailHeaders.REL_SUCCESS); splits.get(0).assertAttributeEquals("email.headers.from.0", from); splits.get(0).assertAttributeExists("email.headers.mime-version"); splits.get(0).assertAttributeNotExists("email.headers.to"); splits.get(0).assertAttributeNotExists("email.headers.cc"); splits.get(0).assertAttributeNotExists("email.headers.bcc"); }
Example 14
Source File: RepositoryExporter.java From document-management-system with GNU General Public License v2.0 | 5 votes |
/** * Export mail from OpenKM repository to filesystem. */ public static ImpExpStats exportMail(String token, String mailPath, String destPath, boolean metadata, Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException, IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException { MailModule mm = ModuleManager.getMailModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); Mail mailChild = mm.getProperties(token, mailPath); Gson gson = new Gson(); ImpExpStats stats = new ImpExpStats(); MimeMessage msg = MailUtils.create(token, mailChild); FileOutputStream fos = new FileOutputStream(destPath); msg.writeTo(fos); IOUtils.closeQuietly(fos); FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath()); // Metadata if (metadata) { MailMetadata mmd = ma.getMetadata(mailChild); String json = gson.toJson(mmd); fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT); IOUtils.write(json, fos); IOUtils.closeQuietly(fos); } if (out != null) { out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + mailChild.getSize()); stats.setMails(stats.getMails() + 1); return stats; }
Example 15
Source File: EwsExchangeSession.java From davmail with GNU General Public License v2.0 | 4 votes |
/** * Get item content. * * @param itemId EWS item id * @return item content as byte array * @throws IOException on error */ protected byte[] getContent(ItemId itemId) throws IOException { GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true); byte[] mimeContent = null; try { executeMethod(getItemMethod); mimeContent = getItemMethod.getMimeContent(); } catch (EWSException e) { LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage()); } if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new HttpNotFoundException("Item " + itemId + " not found"); } if (mimeContent == null) { LOGGER.warn("MimeContent not available, trying to rebuild from properties"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false); getItemMethod.addAdditionalProperty(Field.get("contentclass")); getItemMethod.addAdditionalProperty(Field.get("message-id")); getItemMethod.addAdditionalProperty(Field.get("from")); getItemMethod.addAdditionalProperty(Field.get("to")); getItemMethod.addAdditionalProperty(Field.get("cc")); getItemMethod.addAdditionalProperty(Field.get("subject")); getItemMethod.addAdditionalProperty(Field.get("date")); getItemMethod.addAdditionalProperty(Field.get("body")); executeMethod(getItemMethod); EWSMethod.Item item = getItemMethod.getResponseItem(); if (item == null) { throw new HttpNotFoundException("Item " + itemId + " not found"); } MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName())); mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName()))); mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName())); mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName())); mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName())); mimeMessage.setSubject(item.get(Field.get("subject").getResponseName())); String propertyValue = item.get(Field.get("body").getResponseName()); if (propertyValue == null) { propertyValue = ""; } mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); mimeMessage.writeTo(baos); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray(), StandardCharsets.UTF_8)); } mimeContent = baos.toByteArray(); } catch (IOException | MessagingException e2) { LOGGER.warn(e2); } if (mimeContent == null) { throw new IOException("GetItem returned null MimeContent"); } } return mimeContent; }
Example 16
Source File: SendMessage.java From aws-doc-sdk-examples with Apache License 2.0 | 4 votes |
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 17
Source File: GmailSendEmailCustomizer.java From syndesis with Apache License 2.0 | 4 votes |
private static com.google.api.services.gmail.model.Message createMessage(String to, String from, String subject, String bodyText, String cc, String bcc) throws MessagingException, IOException { if (ObjectHelper.isEmpty(to)) { throw new RuntimeCamelException("Cannot create gmail message as no 'to' address is available"); } if (ObjectHelper.isEmpty(from)) { throw new RuntimeCamelException("Cannot create gmail message as no 'from' address is available"); } if (ObjectHelper.isEmpty(subject)) { LOG.warn("New gmail message wil have no 'subject'. This may not be want you wanted?"); } if (ObjectHelper.isEmpty(bodyText)) { LOG.warn("New gmail message wil have no 'body text'. This may not be want you wanted?"); } Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.addRecipients(javax.mail.Message.RecipientType.TO, getAddressesList(to)); email.setSubject(subject); email.setText(bodyText); if (ObjectHelper.isNotEmpty(cc)) { email.addRecipients(javax.mail.Message.RecipientType.CC, getAddressesList(cc)); } if (ObjectHelper.isNotEmpty(bcc)) { email.addRecipients(javax.mail.Message.RecipientType.BCC, getAddressesList(bcc)); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); email.writeTo(buffer); byte[] bytes = buffer.toByteArray(); String encodedEmail = Base64.encodeBase64URLSafeString(bytes); com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message(); message.setRaw(encodedEmail); return message; }
Example 18
Source File: SesSendNotificationHandler.java From smart-security-camera with GNU General Public License v3.0 | 4 votes |
public Parameters handleRequest(Parameters parameters, Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); try { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setSubject(EMAIL_SUBJECT, "UTF-8"); message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM"))); message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) }); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT"))); MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); wrap.setContent(cover); MimeMultipart content = new MimeMultipart("related"); message.setContent(content); content.addBodyPart(wrap); URL attachmentURL = new URL( System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key()); StringBuilder sb = new StringBuilder(); String id = UUID.randomUUID().toString(); sb.append("<img src=\"cid:"); sb.append(id); sb.append("\" alt=\"ATTACHMENT\"/>\n"); MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new URLDataSource(attachmentURL); attachment.setDataHandler(new DataHandler(fds)); attachment.setContentID("<" + id + ">"); attachment.setDisposition("attachment"); attachment.setFileName(fds.getName()); content.addBodyPart(attachment); String prettyPrintLabels = parameters.getRekognitionLabels().toString(); prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", ""); prettyPrintLabels = prettyPrintLabels.replace(",", "<br>"); html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "") + "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID() + "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb + "</body></html>", "text/html"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendRawEmail(rawEmailRequest); // Convert Checked Exceptions to RuntimeExceptions to ensure that // they get picked up by the Step Function infrastructure } catch (MessagingException | IOException e) { throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e); } context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); return parameters; }
Example 19
Source File: SendMessageAttachment.java From aws-doc-sdk-examples with Apache License 2.0 | 4 votes |
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 20
Source File: AbstractDavMailTestCase.java From davmail with GNU General Public License v2.0 | 3 votes |
/** * Convert MIME message to byte array. * @param mimeMessage mime message * @return content * @throws IOException on error * @throws MessagingException on error */ @SuppressWarnings("unused") protected byte[] getMimeBody(MimeMessage mimeMessage) throws IOException, MessagingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); return baos.toByteArray(); }