下面列出了怎么用javax.mail.internet.MimeMessage.RecipientType的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testOutgoingMessage() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.TO, "[email protected]");
runner.enqueue("Some Text".getBytes());
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("Message Body", message.getContent());
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}
@Test
public void testSendAndWaitForIncomingMailsInBcc() throws Throwable {
String subject = GreenMailUtil.random();
String body = GreenMailUtil.random();
final MimeMessage message = createTextEmail("[email protected]", "[email protected]", subject, body, greenMail.getSmtp().getServerSetup());
message.addRecipients(Message.RecipientType.BCC, "[email protected],[email protected]");
assertEquals(0, greenMail.getReceivedMessages().length);
GreenMailUtil.sendMimeMessage(message);
assertTrue(greenMail.waitForIncomingEmail(1500, 3));
MimeMessage[] emails = greenMail.getReceivedMessages();
assertEquals(3, emails.length);
}
@Test
public void testSmtpServerReceiveWithAUTHSuffix() throws Throwable {
assertEquals(0, greenMail.getReceivedMessages().length);
String subject = GreenMailUtil.random();
Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.from", "<[email protected]> AUTH <somethingidontknow>");
Session session = GreenMailUtil.getSession(ServerSetupTest.SMTP, mailProps);
MimeMessage message = new MimeMessage(session);
message.setContent("body1", "text/plain");
message.setFrom("[email protected]");
message.setRecipients(RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject(subject);
GreenMailUtil.sendMimeMessage(message);
System.setProperty("mail.smtp.from", "<[email protected]> AUTH <somethingidontknow>");
greenMail.waitForIncomingEmail(1500, 1);
MimeMessage[] emails = greenMail.getReceivedMessages();
assertEquals(1, emails.length);
assertEquals(subject, emails[0].getSubject());
}
@Test
public void testOutgoingMessage() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.TO, "[email protected]");
runner.enqueue("Some Text".getBytes());
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("Message Body", message.getContent());
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}
@Test
public void testOutgoingMessageWithOptionalProperties() throws Exception {
// verifies that optional attributes are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "${from}");
runner.setProperty(PutEmail.MESSAGE, "${message}");
runner.setProperty(PutEmail.TO, "${to}");
runner.setProperty(PutEmail.BCC, "${bcc}");
runner.setProperty(PutEmail.CC, "${cc}");
Map<String, String> attributes = new HashMap<>();
attributes.put("from", "[email protected] <NiFi>");
attributes.put("message", "the message body");
attributes.put("to", "[email protected]");
attributes.put("bcc", "[email protected]");
attributes.put("cc", "[email protected]");
runner.enqueue("Some Text".getBytes(), attributes);
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("\"[email protected]\" <NiFi>", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("the message body", message.getContent());
assertEquals(1, message.getRecipients(RecipientType.TO).length);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertEquals(1, message.getRecipients(RecipientType.BCC).length);
assertEquals("[email protected]", message.getRecipients(RecipientType.BCC)[0].toString());
assertEquals(1, message.getRecipients(RecipientType.CC).length);
assertEquals("[email protected]",message.getRecipients(RecipientType.CC)[0].toString());
}
/**
* Test for CC / BCC
* @throws Exception
*/
@Test
public void testSendingToCarbonCopy() throws IOException, MessagingException
{
// PARAM_TO variant
Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_CC, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing CARBON COPY");
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());
ACTION_SERVICE.executeAction(mailAction, null);
MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
Assert.assertNotNull(message);
Address[] all = message.getAllRecipients();
Address[] ccs = message.getRecipients(RecipientType.CC);
Address[] bccs = message.getRecipients(RecipientType.BCC);
Assert.assertEquals(3, all.length);
Assert.assertEquals(1, ccs.length);
Assert.assertEquals(1, bccs.length);
Assert.assertTrue(ccs[0].toString().contains("some.carbon"));
Assert.assertTrue(bccs[0].toString().contains("some.blindcarbon"));
}
/**
* ALF-21948
*/
@Test
public void testSendingToArrayOfCarbonCopyAndBlindCarbonCopyUsers() throws MessagingException
{
Map<String, Serializable> params = new HashMap<String, Serializable>();
String[] ccArray = { "[email protected]", "[email protected]" };
String[] bccArray = { "[email protected]", "[email protected]", "[email protected]" };
params.put(MailActionExecuter.PARAM_FROM, "[email protected]");
params.put(MailActionExecuter.PARAM_TO, "[email protected]");
params.put(MailActionExecuter.PARAM_CC, ccArray);
params.put(MailActionExecuter.PARAM_BCC, bccArray);
params.put(MailActionExecuter.PARAM_TEXT, "Mail body here");
params.put(MailActionExecuter.PARAM_SUBJECT, "Subject text");
Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME, params);
ACTION_EXECUTER.resetTestSentCount();
ACTION_SERVICE.executeAction(mailAction, null);
MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
Assert.assertNotNull(message);
Address[] all = message.getAllRecipients();
Address[] ccs = message.getRecipients(RecipientType.CC);
Address[] bccs = message.getRecipients(RecipientType.BCC);
Assert.assertEquals(6, all.length);
Assert.assertEquals(2, ccs.length);
Assert.assertEquals(3, bccs.length);
Assert.assertTrue(ccs[0].toString().contains("cc_user1") && ccs[1].toString().contains("cc_user2"));
Assert.assertTrue(bccs[0].toString().contains("bcc_user3") && bccs[1].toString().contains("bcc_user4")
&& bccs[2].toString().contains("bcc_user5"));
}
/**
* ALF-21948
*/
@Test
public void testSendingToListOfCarbonCopyAndBlindCarbonCopyUsers() throws MessagingException
{
List<String> ccList = new ArrayList<String>();
ccList.add("[email protected]");
ccList.add("[email protected]");
List<String> bccList = new ArrayList<String>();
bccList.add("[email protected]");
bccList.add("[email protected]");
bccList.add("[email protected]");
Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_TO, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_CC, (Serializable) ccList);
mailAction.setParameterValue(MailActionExecuter.PARAM_BCC, (Serializable) bccList);
mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing (BLIND) CARBON COPY");
mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "mail body here");
ACTION_EXECUTER.resetTestSentCount();
ACTION_SERVICE.executeAction(mailAction, null);
MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
Assert.assertNotNull(message);
Address[] all = message.getAllRecipients();
Address[] ccs = message.getRecipients(RecipientType.CC);
Address[] bccs = message.getRecipients(RecipientType.BCC);
Assert.assertEquals(6, all.length);
Assert.assertEquals(2, ccs.length);
Assert.assertEquals(3, bccs.length);
Assert.assertTrue(ccs[0].toString().contains("cc_user1") && ccs[1].toString().contains("cc_user2"));
Assert.assertTrue(bccs[0].toString().contains("bcc_user3") && bccs[1].toString().contains("bcc_user4")
&& bccs[2].toString().contains("bcc_user5"));
}
@Test(expected = APPlatformException.class)
public void testComposeMessage_addRecipientsFails() throws Exception {
// given
MimeMessage mockMessage = mock(MimeMessage.class);
doThrow(new MessagingException("Adding recipient addresses fails."))
.when(mockMessage).addRecipients(any(RecipientType.class),
any(Address[].class));
doReturn(mockMessage).when(commService).getMimeMessage(
any(Session.class));
// when
commService
.composeMessage(Collections.singletonList("[email protected]"),
"subject", "text");
}
private MimeMessage verifyHeaders(String subject) throws MessagingException {
FakeMailContext.SentMail sentMail = FakeMailContext.sentMailBuilder()
.recipient(new MailAddress(USERNAME.asString()))
.sender(new MailAddress(SIEVE_LOCALHOST))
.fromMailet()
.build();
assertThat(fakeMailContext.getSentMails()).containsOnly(sentMail);
MimeMessage result = fakeMailContext.getSentMails().get(0).getMsg();
assertThat(result.getSubject()).isEqualTo(subject);
assertThat(result.getRecipients(RecipientType.TO)).containsOnly(new InternetAddress(USERNAME.asString()));
return result;
}
@Test
public void testOutgoingMessageWithFlowfileContent() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected],[email protected]");
runner.setProperty(PutEmail.MESSAGE, "${body}");
runner.setProperty(PutEmail.TO, "[email protected],[email protected]");
runner.setProperty(PutEmail.CC, "[email protected],[email protected]");
runner.setProperty(PutEmail.BCC, "[email protected],[email protected]");
runner.setProperty(PutEmail.CONTENT_AS_MESSAGE, "${sendContent}");
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("sendContent", "true");
attributes.put("body", "Message Body");
runner.enqueue("Some Text".getBytes(), attributes);
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("[email protected]", message.getFrom()[1].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("Some Text", message.getContent());
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[1].toString());
assertEquals("[email protected]", message.getRecipients(RecipientType.CC)[0].toString());
assertEquals("[email protected]", message.getRecipients(RecipientType.CC)[1].toString());
assertEquals("[email protected]", message.getRecipients(RecipientType.BCC)[0].toString());
assertEquals("[email protected]", message.getRecipients(RecipientType.BCC)[1].toString());
}
public static String assertEmailAndGetUrl(String from, String recipient, String content, Boolean sslEnabled) {
try {
MimeMessage message;
if (sslEnabled){
message= SslMailServer.getLastReceivedMessage();
} else {
message = MailServer.getLastReceivedMessage();
}
assertNotNull("There is no received email.", message);
assertEquals(recipient, message.getRecipients(RecipientType.TO)[0].toString());
assertEquals(from, message.getFrom()[0].toString());
String messageContent;
if (message.getContent() instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
// TEXT content is on index 0
messageContent = String.valueOf(mimeMultipart.getBodyPart(0).getContent());
} else {
messageContent = String.valueOf(message.getContent());
}
logMessageContent(messageContent);
String errorMessage = "Email content should contains \"" + content
+ "\", but it doesn't.\nEmail content:\n" + messageContent + "\n";
assertTrue(errorMessage, messageContent.contains(content));
for (String string : messageContent.split("\n")) {
if (string.startsWith("http")) {
// Ampersand escaped in the text version. Needs to be replaced to have correct URL
string = string.replace("&", "&");
return string;
}
}
return null;
} catch (IOException | MessagingException | InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) throws Exception {
MailServer.start();
MailServer.createEmailAccount("[email protected]", "password");
try {
while (true) {
int c = greenMail.getReceivedMessages().length;
if (greenMail.waitForIncomingEmail(Long.MAX_VALUE, c + 1)) {
MimeMessage m = greenMail.getReceivedMessages()[c++];
log.info("-------------------------------------------------------");
log.info("Received mail to " + m.getRecipients(RecipientType.TO)[0]);
if (m.getContent() instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) m.getContent();
for (int i = 0; i < mimeMultipart.getCount(); i++) {
log.info("----");
log.info(mimeMultipart.getBodyPart(i).getContentType() + ":\n");
log.info(mimeMultipart.getBodyPart(i).getContent());
}
} else {
log.info("\n" + m.getContent());
}
log.info("-------------------------------------------------------");
}
}
} catch (IOException | InterruptedException | MessagingException ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) throws Exception {
ServerSetup setup = new ServerSetup(3025, "localhost", "smtp");
GreenMail greenMail = new GreenMail(setup);
greenMail.start();
System.out.println("Started mail server (localhost:3025)");
System.out.println();
while (true) {
int c = greenMail.getReceivedMessages().length;
if (greenMail.waitForIncomingEmail(Long.MAX_VALUE, c + 1)) {
MimeMessage message = greenMail.getReceivedMessages()[c++];
System.out.println("-------------------------------------------------------");
System.out.println("Received mail to " + message.getRecipients(RecipientType.TO)[0]);
if (message.getContent() instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
for (int i = 0; i < mimeMultipart.getCount(); i++) {
System.out.println("----");
System.out.println(mimeMultipart.getBodyPart(i).getContentType() + ":");
System.out.println();
System.out.println(mimeMultipart.getBodyPart(i).getContent());
}
} else {
System.out.println();
System.out.println(message.getContent());
}
System.out.println("-------------------------------------------------------");
}
}
}
@Test
public void testOutgoingMessageAttachment() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.ATTACH_FILE, "true");
runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
runner.setProperty(PutEmail.TO, "[email protected]");
runner.enqueue("Some text".getBytes());
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertTrue(message.getContent() instanceof MimeMultipart);
final MimeMultipart multipart = (MimeMultipart) message.getContent();
final BodyPart part = multipart.getBodyPart(0);
final InputStream is = part.getDataHandler().getInputStream();
final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
assertEquals("Message Body", decodedText);
final BodyPart attachPart = multipart.getBodyPart(1);
final InputStream attachIs = attachPart.getDataHandler().getInputStream();
final String text = IOUtils.toString(attachIs, "UTF-8");
assertEquals("Some text", text);
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}
@Test
public void testPrepareEmailForDisabledUsers() throws MessagingException
{
String groupName = null;
final String USER1 = "test_user1";
final String USER2 = "test_user2";
try
{
createUser(USER1, null);
NodeRef userNode = createUser(USER2, null);
groupName = AUTHORITY_SERVICE.createAuthority(AuthorityType.GROUP, "testgroup1");
AUTHORITY_SERVICE.addAuthority(groupName, USER1);
AUTHORITY_SERVICE.addAuthority(groupName, USER2);
NODE_SERVICE.addAspect(userNode, ContentModel.ASPECT_PERSON_DISABLED, null);
final Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, groupName);
mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
mailAction.setParameterValue(MailActionExecuter.PARAM_TEXT, "Testing");
RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
MimeMessage mm = txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
{
@Override
public MimeMessage execute() throws Throwable
{
return ACTION_EXECUTER.prepareEmail(mailAction, null, null, null).getMimeMessage();
}
}, true);
Address[] addresses = mm.getRecipients(Message.RecipientType.TO);
Assert.assertEquals(1, addresses.length);
Assert.assertEquals(USER1 + "@email.com", addresses[0].toString());
}
finally
{
if (groupName != null)
{
AUTHORITY_SERVICE.deleteAuthority(groupName, true);
}
PERSON_SERVICE.deletePerson(USER1);
PERSON_SERVICE.deletePerson(USER2);
}
}
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsText(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.setText("An 8bit encoded body with €uro symbol.", "ISO-8859-15");
Mailet mailet = new DKIMSign();
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();
mailet.init(mci);
Mail mail = FakeMail.builder()
.name("test")
.mimeMessage(mm)
.build();
Mailet m7bit = new ConvertTo7Bit();
m7bit.init(mci);
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");
verify(rawMessage, mockPublicKeyRecordRetriever);
}
@ParameterizedTest
@ValueSource(strings = {PKCS1_PEM_FILE, PKCS8_PEM_FILE})
void testDKIMSignMessageAsObjectConvertedTo7Bit(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");
verify(rawMessage, mockPublicKeyRecordRetriever);
}
@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
}
}
@Test
public void testOutgoingMessageWithOptionalProperties() throws Exception {
// verifies that optional attributes are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNíFiNonASCII");
runner.setProperty(PutEmail.FROM, "${from}");
runner.setProperty(PutEmail.MESSAGE, "${message}");
runner.setProperty(PutEmail.TO, "${to}");
runner.setProperty(PutEmail.BCC, "${bcc}");
runner.setProperty(PutEmail.CC, "${cc}");
runner.setProperty(PutEmail.ATTRIBUTE_NAME_REGEX, "Precedence.*");
Map<String, String> attributes = new HashMap<>();
attributes.put("from", "[email protected] <NiFi>");
attributes.put("message", "the message body");
attributes.put("to", "[email protected]");
attributes.put("bcc", "[email protected]");
attributes.put("cc", "[email protected]");
attributes.put("Precedence", "bulk");
attributes.put("PrecedenceEncodeDecodeTest", "búlk");
runner.enqueue("Some Text".getBytes(), attributes);
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("\"[email protected]\" <NiFi>", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNíFiNonASCII", MimeUtility.decodeText(message.getHeader("X-Mailer")[0]));
assertEquals("the message body", message.getContent());
assertEquals(1, message.getRecipients(RecipientType.TO).length);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertEquals(1, message.getRecipients(RecipientType.BCC).length);
assertEquals("[email protected]", message.getRecipients(RecipientType.BCC)[0].toString());
assertEquals(1, message.getRecipients(RecipientType.CC).length);
assertEquals("[email protected]",message.getRecipients(RecipientType.CC)[0].toString());
assertEquals("bulk", MimeUtility.decodeText(message.getHeader("Precedence")[0]));
assertEquals("búlk", MimeUtility.decodeText(message.getHeader("PrecedenceEncodeDecodeTest")[0]));
}
@Test
public void testOutgoingMessageAttachment() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.ATTACH_FILE, "true");
runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
runner.setProperty(PutEmail.TO, "[email protected]");
Map<String, String> attributes = new HashMap<>();
attributes.put(CoreAttributes.FILENAME.key(), "test한的ほу́.pdf");
runner.enqueue("Some text".getBytes(), attributes);
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertTrue(message.getContent() instanceof MimeMultipart);
final MimeMultipart multipart = (MimeMultipart) message.getContent();
final BodyPart part = multipart.getBodyPart(0);
final InputStream is = part.getDataHandler().getInputStream();
final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
assertEquals("Message Body", decodedText);
final BodyPart attachPart = multipart.getBodyPart(1);
final InputStream attachIs = attachPart.getDataHandler().getInputStream();
final String text = IOUtils.toString(attachIs, "UTF-8");
assertEquals("test한的ほу́.pdf", MimeUtility.decodeText(attachPart.getFileName()));
assertEquals("Some text", text);
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}