Java Code Examples for javax.mail.internet.MimeMessage#saveChanges()
The following examples show how to use
javax.mail.internet.MimeMessage#saveChanges() .
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: EMailManager.java From jforgame with Apache License 2.0 | 6 votes |
/** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String title, String content) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(sendMail, "昵称", "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8")); // 4. Subject: 邮件主题 message.setSubject(title, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; }
Example 2
Source File: EmailTest.java From commons-email with Apache License 2.0 | 6 votes |
/** * Case 3: * A non-text content object ignores a default charset entirely. * @throws Exception on any error */ @Test public void testDefaultCharsetIgnoredByNonTextContent() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("[email protected]"); email.addTo("[email protected]"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); email.setContent("test content", "application/octet-stream"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("application/octet-stream", msg.getContentType()); }
Example 3
Source File: EmailTest.java From commons-email with Apache License 2.0 | 6 votes |
@Test public void testCorrectContentTypeForPNG() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("[email protected]"); email.addTo("[email protected]"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); final File png = new File("./target/test-classes/images/logos/maven-feather.png"); email.setContent(png, "image/png"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("image/png", msg.getContentType()); }
Example 4
Source File: JavamailService.java From lemon with Apache License 2.0 | 5 votes |
public void send(String to, String cc, String bcc, String subject, String content, JavamailConfig javamailConfig) throws MessagingException { logger.debug("send : {}, {}", to, subject); try { Properties props = createSmtpProperties(javamailConfig); String username = javamailConfig.getUsername(); String password = javamailConfig.getPassword(); // 创建Session实例对象 Session session = Session.getInstance(props, new SmtpAuthenticator( username, password)); session.setDebug(false); // 创建MimeMessage实例对象 MimeMessage message = new MimeMessage(session); // 设置邮件主题 message.setSubject(subject); // 设置发送人 message.setFrom(new InternetAddress(username)); // 设置发送时间 message.setSentDate(new Date()); // 设置收件人 message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk message.setContent(content, "text/html;charset=gbk"); // 保存并生成最终的邮件内容 message.saveChanges(); // 发送邮件 Transport.send(message); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
Example 5
Source File: ClamAVScan.java From james-project with Apache License 2.0 | 5 votes |
/** * Saves changes resetting the original message id. * * @param message the message to save */ protected final void saveChanges(MimeMessage message) throws MessagingException { String messageId = message.getMessageID(); message.saveChanges(); if (messageId != null) { message.setHeader(RFC2822Headers.MESSAGE_ID, messageId); } }
Example 6
Source File: SetMimeHeader.java From james-project with Apache License 2.0 | 5 votes |
@Override public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); message.addHeader(headerName, headerValue); message.saveChanges(); }
Example 7
Source File: ClassifyBounce.java From james-project with Apache License 2.0 | 5 votes |
/** * Takes the message and adds a header to it. * * @param mail the mail being processed * @throws MessagingException if an error arises during message processing */ @Override public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); Classifier classifier = new Classifier(message); String classification = classifier.getClassification(); //if ( !classification.equals("Normal") ) { message.setHeader(headerName, classification); message.saveChanges(); //} }
Example 8
Source File: AutomaticallySentMailDetectorImplTest.java From james-project with Apache License 2.0 | 5 votes |
@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: EmailTest.java From commons-email with Apache License 2.0 | 5 votes |
@Test public void testFoldingHeaders() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("[email protected]"); email.addTo("[email protected]"); email.setSubject("test mail"); final String headerValue = "1234567890 1234567890 123456789 01234567890 123456789 0123456789 01234567890 01234567890"; email.addHeader("X-LongHeader", headerValue); assertTrue(email.getHeaders().size() == 1); // the header should not yet be folded -> will be done by buildMimeMessage() assertFalse(email.getHeaders().get("X-LongHeader").contains("\r\n")); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); final String[] values = msg.getHeader("X-LongHeader"); assertEquals(1, values.length); // the header should be split in two lines final String[] lines = values[0].split("\\r\\n"); assertEquals(2, lines.length); // there should only be one line-break assertTrue(values[0].indexOf("\n") == values[0].lastIndexOf("\n")); }
Example 10
Source File: ManageSieveMailetTestCase.java From james-project with Apache License 2.0 | 5 votes |
@Test public final void testCapabilityExtraArguments() throws Exception { MimeMessage message = prepareMimeMessage("CAPABILITY"); Mail mail = createUnauthenticatedMail(message); message.setSubject("CAPABILITY extra"); message.saveChanges(); mailet.service(mail); ensureResponse("Re: CAPABILITY extra", "NO \"Too many arguments: extra\""); }
Example 11
Source File: AutomaticallySentMailDetectorImplTest.java From james-project with Apache License 2.0 | 5 votes |
@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 12
Source File: EmailSmtpConnector.java From mxisd with GNU Affero General Public License v3.0 | 4 votes |
@Override public void send(String senderAddress, String senderName, String recipient, String content) { if (StringUtils.isBlank(senderAddress)) { throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " + "You must set a value for notifications to work"); } if (StringUtils.isBlank(content)) { throw new InternalServerError("Notification content is empty"); } try { InternetAddress sender = new InternetAddress(senderAddress, senderName); MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8)); // We must encode our headers ourselves as we have no guarantee that they were in the provided data. // This is required to support UTF-8 characters from user display names or room names in the subject header per example Enumeration<Header> headers = msg.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue())); } msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent)); msg.setSentDate(new Date()); msg.setFrom(sender); msg.setRecipients(Message.RecipientType.TO, recipient); msg.saveChanges(); log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); if (cfg.getTls() < 3) { transport.setStartTLS(cfg.getTls() > 0); transport.setRequireStartTLS(cfg.getTls() > 1); } log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort()); if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) { log.info("Not using SMTP authentication"); transport.connect(); } else { log.info("Using SMTP authentication"); transport.connect(cfg.getLogin(), cfg.getPassword()); } try { transport.sendMessage(msg, InternetAddress.parse(recipient)); log.info("Invite to {} was sent", recipient); } finally { transport.close(); } } catch (UnsupportedEncodingException | MessagingException e) { throw new RuntimeException("Unable to send e-mail invite to " + recipient, e); } }
Example 13
Source File: Converter7Bit.java From james-project with Apache License 2.0 | 4 votes |
public void convertTo7Bit(MimeMessage mimeMessage) throws MessagingException, IOException { convertPart(mimeMessage); mimeMessage.saveChanges(); }
Example 14
Source File: AbstractSign.java From james-project with Apache License 2.0 | 4 votes |
/** * Service does the hard work, and signs * * @param mail the mail to sign * @throws MessagingException if a problem arises signing the mail */ @Override public void service(Mail mail) throws MessagingException { try { if (!isOkToSign(mail)) { return; } MimeBodyPart wrapperBodyPart = getWrapperBodyPart(mail); MimeMessage originalMessage = mail.getMessage(); // do it MimeMultipart signedMimeMultipart; if (wrapperBodyPart != null) { signedMimeMultipart = getKeyHolder().generate(wrapperBodyPart); } else { signedMimeMultipart = getKeyHolder().generate(originalMessage); } MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); Enumeration<String> headerEnum = originalMessage.getAllHeaderLines(); while (headerEnum.hasMoreElements()) { newMessage.addHeaderLine(headerEnum.nextElement()); } newMessage.setSender(new InternetAddress(getKeyHolder().getSignerAddress(), getSignerName())); if (isRebuildFrom()) { // builds a new "mixed" "From:" header InternetAddress modifiedFromIA = new InternetAddress(getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString()); newMessage.setFrom(modifiedFromIA); // if the original "ReplyTo:" header is missing sets it to the original "From:" header newMessage.setReplyTo(originalMessage.getReplyTo()); } newMessage.setContent(signedMimeMultipart, signedMimeMultipart.getContentType()); String messageId = originalMessage.getMessageID(); newMessage.saveChanges(); if (messageId != null) { newMessage.setHeader(RFC2822Headers.MESSAGE_ID, messageId); } mail.setMessage(newMessage); // marks this mail as server-signed mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNING_MAILET, AttributeValue.of(this.getClass().getName()))); // it is valid for us by definition (signed here by us) mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNATURE_VALIDITY, AttributeValue.of("valid"))); // saves the trusted server signer address // warning: should be same as the mail address in the certificate, but it is not guaranteed mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNER_ADDRESS, AttributeValue.of(getKeyHolder().getSignerAddress()))); if (isDebug()) { LOGGER.debug("Message signed, reverse-path: {}, Id: {}", mail.getMaybeSender().asString(), messageId); } } catch (MessagingException me) { LOGGER.error("MessagingException found - could not sign!", me); throw me; } catch (Exception e) { LOGGER.error("Exception found", e); throw new MessagingException("Exception thrown - could not sign!", e); } }
Example 15
Source File: SendMail.java From xunxian with Apache License 2.0 | 4 votes |
/** * * @param targetMail 发送至的账号 * @param title 发送的标题 * @param content 发送的内容 */ public void sendMail(String targetMail,String title,String content) { try { properties = new Properties(); //设置邮件服务器 properties.put("mail.smtp.host", "smtp.163.com"); //验证 properties.put("mail.smtp.auth", "true"); //根据属性新建一个邮件会话 mailSession = Session.getInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "cccccc"); } }); mailSession.setDebug(true); //建立消息对象 mailMessage = new MimeMessage(mailSession); //发件人 mailMessage.setFrom(new InternetAddress("[email protected]")); //收件人 mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(targetMail)); //主题 mailMessage.setSubject(title); //内容 mailMessage.setText(content); //发信时间 mailMessage.setSentDate(new Date()); //存储信息 mailMessage.saveChanges(); // trans = mailSession.getTransport("smtp"); //发送 trans.send(mailMessage); } catch (Exception e) { new File().log("邮件发送失败异常捕获:"+e.getMessage()); e.printStackTrace(); } finally { } }
Example 16
Source File: DKIMSignTest.java From james-project with Apache License 2.0 | 4 votes |
@ParameterizedTest @ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE}) void testDKIMSignMessageAsObjectNotConverted(String pemFile) throws MessagingException, IOException, FailException { MimeMessage mm = new MimeMessage(Session .getDefaultInstance(new Properties())); mm.addFrom(new Address[]{new InternetAddress("[email protected]")}); mm.addRecipient(RecipientType.TO, new InternetAddress("[email protected]")); mm.setContent("An 8bit encoded body with €uro symbol.", "text/plain; charset=iso-8859-15"); mm.setHeader("Content-Transfer-Encoding", "8bit"); mm.saveChanges(); FAKE_MAIL_CONTEXT.getServerInfo(); FakeMailetConfig mci = FakeMailetConfig.builder() .mailetName("Test") .mailetContext(FAKE_MAIL_CONTEXT) .setProperty( "signatureTemplate", "v=1; s=selector; d=example.com; h=from:to:received:received; a=rsa-sha256; bh=; b=;") .setProperty("privateKeyFilepath", pemFile) .build(); Mail mail = FakeMail.builder() .name("test") .mimeMessage(mm) .build(); Mailet mailet = new DKIMSign(); mailet.init(mci); Mailet m7bit = new ConvertTo7Bit(); m7bit.init(mci); // m7bit.service(mail); mailet.service(mail); m7bit.service(mail); ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mail.getMessage().writeTo(rawMessage); MockPublicKeyRecordRetriever mockPublicKeyRecordRetriever = new MockPublicKeyRecordRetriever( "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;", "selector", "example.com"); try { verify(rawMessage, mockPublicKeyRecordRetriever); fail("Expected PermFail"); } catch (PermFailException e) { // do nothing } }
Example 17
Source File: MailUtil.java From jeecg with Apache License 2.0 | 4 votes |
/** * 发送电子邮件 * * @param smtpHost * 发信主机 * @param receiver * 邮件接收者 * @param copy * 抄送列表 * @param title * 邮件的标题 * @param content * 邮件的内容 * @param sender * 邮件发送者 * @param user * 发送者邮箱用户名 * @param pwd * 发送者邮箱密码 * @throws Exception */ public static void sendEmail(String smtpHost, String receiver, String copy, String title, String content, String sender, String user, String pwd) throws Exception { Properties props = new Properties(); props.put("mail.host", smtpHost); props.put("mail.transport.protocol", "smtp"); // props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动! props.put("mail.smtp.auth", "true"); Session s = Session.getDefaultInstance(props); s.setDebug(true); MimeMessage message = new MimeMessage(s); // 给消息对象设置发件人/收件人/主题/发信时间 // 发件人的邮箱 InternetAddress from = new InternetAddress(sender); message.setFrom(from); String[] receivers = receiver.split(","); InternetAddress[] to = new InternetAddress[receivers.length]; for (int i = 0; i < receivers.length; i++) { to[i] = new InternetAddress(receivers[i]); } message.setRecipients(Message.RecipientType.TO, to); String[] copys = copy.split(","); InternetAddress[] cc = new InternetAddress[copys.length]; for (int i = 0; i < copys.length; i++) { cc[i] = new InternetAddress(copys[i]); } message.setRecipients(Message.RecipientType.CC, cc); message.setSubject(title); message.setSentDate(new Date()); // 给消息对象设置内容 BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象 mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码 Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对 // 象(事实上可以存放多个) mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart) message.setContent(mm);// 把mm作为消息对象的内容 message.saveChanges(); Transport transport = s.getTransport("smtp"); transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的 transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
Example 18
Source File: Tool.java From EasyHousing with MIT License | 4 votes |
private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String password) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sendMail, "易购房", "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "亲爱的用户", "UTF-8")); // 4. Subject: 主题 message.setSubject("找回密码", "UTF-8"); // 5. Content: 内容 message.setContent("您好,以下为您的密码,请及时修改~\n" + "密码:" + password, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; }
Example 19
Source File: SMimePackageEncryptor.java From ats-framework with Apache License 2.0 | 4 votes |
@PublicAtsApi public Package sign( Package sourcePackage ) throws ActionException { try { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } KeyStore ks = getKeystore(); // TODO wrap exception with possible causes and add some hint PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray()); // Get whole certificate chain Certificate[] certArr = ks.getCertificateChain(aliasOrCN); // Pre 4.0.6 behavior was not to attach full cert. chain X509Certificate cer = (X509Certificate) ks.getCertificate(aliasOrCN); if (certArr.length >= 1) { LOG.debug("Found certificate of alias: " + aliasOrCN + ". Lenght of cert chain: " + certArr.length + ", child cert:" + certArr[0].toString()); } X509Certificate childCert = (X509Certificate) certArr[0]; /* Create the SMIMESignedGenerator */ ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(childCert.getIssuerDN() .getName()), childCert.getSerialNumber()))); SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.aES128_CBC); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); if (signatureAlgorithm == null) { // not specified explicitly // TODO check defaults to be used signatureAlgorithm = SignatureAlgorithm.DSA.equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA"; } SMIMESignedGenerator signer = new SMIMESignedGenerator(); JcaSimpleSignerInfoGeneratorBuilder signerGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder(); signerGeneratorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); signerGeneratorBuilder.setSignedAttributeGenerator(new AttributeTable(attributes)); signer.addSignerInfoGenerator(signerGeneratorBuilder.build(signatureAlgorithm, privateKey, childCert)); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); for (int i = 0; i < certArr.length; i++) { // first add child cert, and CAs certList.add((X509Certificate) certArr[i]); } Store<?> certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ Session session = Session.getDefaultInstance(System.getProperties(), null); MimeMultipart mm = signer.generate(getMimeMessage(sourcePackage)); MimeMessage signedMessage = new MimeMessage(session); /* Set all original MIME headers in the signed message */ Enumeration<?> headers = getMimeMessage(sourcePackage).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); return new MimePackage(signedMessage); } catch (Exception e) { throw new ActionException(EXCEPTION_WHILE_SIGNING, e); } }
Example 20
Source File: Rfc822MessageTest.java From greenmail with Apache License 2.0 | 4 votes |
/** * Structure of test message and content type: * <p> * Message (multipart/mixed) * \--> MultiPart (multipart/mixed) * \--> MimeBodyPart (message/rfc822) * \--> Message (text/plain) */ @Test public void testForwardWithRfc822() throws MessagingException, IOException { greenMail.setUser("foo@localhost", "pwd"); final Session session = greenMail.getSmtp().createSession(); // Message for forwarding Message msgToBeForwarded = GreenMailUtil.createTextEmail( "foo@localhost", "foo@localhost", "test newMessageWithForward", "forwarded mail content", greenMail.getSmtp().getServerSetup()); // Create body part containing forwarded message MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(msgToBeForwarded, "message/rfc822"); // Add message body part to multi part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // New main message, containing body part MimeMessage newMessageWithForward = new MimeMessage(session); newMessageWithForward.setRecipient(Message.RecipientType.TO, new InternetAddress("foo@localhost")); newMessageWithForward.setSubject("Fwd: " + "test"); newMessageWithForward.setFrom(new InternetAddress("foo@localhost")); newMessageWithForward.setContent(multipart); //Save changes in newMessageWithForward message newMessageWithForward.saveChanges(); GreenMailUtil.sendMimeMessage(newMessageWithForward); final IMAPStore store = greenMail.getImap().createStore(); store.connect("foo@localhost", "pwd"); try { Folder inboxFolder = store.getFolder("INBOX"); inboxFolder.open(Folder.READ_WRITE); Message[] messages = inboxFolder.getMessages(); MimeMessage msg = (MimeMessage) messages[0]; assertTrue(msg.getContentType().startsWith("multipart/mixed")); Multipart multipartReceived = (Multipart) msg.getContent(); assertTrue(multipartReceived.getContentType().startsWith("multipart/mixed")); MimeBodyPart mimeBodyPartReceived = (MimeBodyPart) multipartReceived.getBodyPart(0); assertTrue(mimeBodyPartReceived.getContentType().toLowerCase().startsWith("message/rfc822")); MimeMessage msgAttached = (MimeMessage) mimeBodyPartReceived.getContent(); assertThat(msgAttached.getContentType().toLowerCase(), startsWith("text/plain")); assertArrayEquals(msgToBeForwarded.getRecipients(Message.RecipientType.TO), msgAttached.getRecipients(Message.RecipientType.TO)); assertArrayEquals(msgToBeForwarded.getFrom(), msgAttached.getFrom()); assertEquals(msgToBeForwarded.getSubject(), msgAttached.getSubject()); assertEquals(msgToBeForwarded.getContent(), msgAttached.getContent()); } finally { store.close(); } }