下面列出了怎么用javax.mail.internet.InternetAddress的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a MimeMessage using the parameters provided.
*
* @param to Email address of the receiver.
* @param from Email address of the sender, the mailbox account.
* @param subject Subject of the email.
* @param bodyText Body text of the email.
* @return MimeMessage to be used to send email.
* @throws MessagingException
*/
private static MimeMessage createEmail(String to, String from, String subject,
String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
@Test
public void testAddCc2() throws Exception
{
// ====================================================================
// Test Success
// ====================================================================
final String[] testEmailNames = {"Name1", "", null};
final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
arrExpected.add(new InternetAddress("[email protected]", "Name1"));
arrExpected.add(new InternetAddress("[email protected]"));
arrExpected.add(new InternetAddress("[email protected]"));
for (int i = 0; i < VALID_EMAILS.length; i++)
{
// set from
email.addCc(VALID_EMAILS[i], testEmailNames[i]);
}
// retrieve and verify
assertEquals(arrExpected.size(), email.getCcAddresses().size());
assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
}
@Test
public void shouldIgnoreNullTo() throws Exception {
//Arrange
when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));
final DefaultEmail email = DefaultEmail.builder()
.from(getCiceroMainMailAddress())
.replyTo(getCiceroSecondayMailAddress())
.cc(Lists.newArrayList(new InternetAddress("[email protected]", "Titus Lucretius Carus"),
new InternetAddress("[email protected]", "Info Best Seller")))
.bcc(Lists.newArrayList(new InternetAddress("[email protected]", "Caius Memmius")))
.depositionNotificationTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
.receiptTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
.subject("Laelius de amicitia")
.body("Firmamentum autem stabilitatis constantiaeque eius, quam in amicitia quaerimus, fides est.")
.customHeaders(CUSTOM_HEADERS)
.build();
//Act
MimeMessage message = emailToMimeMessage.apply(email);
//Assert
assertions.assertThat(message.getRecipients(Message.RecipientType.TO)).isNullOrEmpty();
}
/**
* Converts addresses in List<String> to InternetAddress array.
*
* @param addressLst a List<String> where each item in list corresponds to one mail
* address
* @return returns array of corresponding InternetAddress for the provided
* List<String> argument
*/
private InternetAddress[] getInternetAddress(List<String> addressLst) {
int size = 0;
if (addressLst != null) {
size = addressLst.size();
}
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
try {
address[i] = new InternetAddress(addressLst.get(i));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return address;
}
public void testJavaMailSenderWithMimeMessage() throws MessagingException {
MockJavaMailSender sender = new MockJavaMailSender();
sender.setHost("host");
sender.setUsername("username");
sender.setPassword("password");
MimeMessage mimeMessage = sender.createMimeMessage();
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
sender.send(mimeMessage);
assertEquals("host", sender.transport.getConnectedHost());
assertEquals("username", sender.transport.getConnectedUsername());
assertEquals("password", sender.transport.getConnectedPassword());
assertTrue(sender.transport.isCloseCalled());
assertEquals(1, sender.transport.getSentMessages().size());
assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
private void verifyMessageSent(String... expectedRecipients) throws Exception {
ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
verify(emailService).sendEmail(contentCaptor.capture());
EmailMessage emailMessage = contentCaptor.getValue();
ImmutableList.Builder<InternetAddress> recipientBuilder = ImmutableList.builder();
for (String expectedRecipient : expectedRecipients) {
recipientBuilder.add(new InternetAddress(expectedRecipient));
}
EmailMessage expectedContent =
EmailMessage.newBuilder()
.setSubject("Welcome to the Internet")
.setBody("It is a dark and scary place.")
.setFrom(new InternetAddress("[email protected]"))
.setRecipients(recipientBuilder.build())
.build();
assertThat(emailMessage).isEqualTo(expectedContent);
}
@Before
public void setUp() throws AddressException, IOException {
String outDirName = "target/output";
Properties properties = new Properties();
outDir = new File(outDirName);
if (outDir.exists()) {
File[] files = outDir.listFiles();
if (files != null) {
for (File f : files) {
if (! f.delete()) {
Logger.getLogger(getClass().getName()).log(Level.WARNING, "Unable to delete test file " + f.getAbsolutePath());
}
}
}
}
properties.put("mail.files.path", outDirName);
session = Session.getDefaultInstance(properties);
toAddress = new Address[] { new InternetAddress("[email protected]") };
outputStream = new ByteArrayOutputStream();
}
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
MockJavaMailSender sender = new MockJavaMailSender();
MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setFrom(new InternetAddress(""));
}
};
try {
sender.send(preparator);
}
catch (MailParseException ex) {
// expected
assertTrue(ex.getCause() instanceof AddressException);
}
}
private static Message createMessage(Session session)
throws MessagingException, IOException {
Message msg = new MimeMessage(session);
InternetAddress fromAddress = new InternetAddress(
getVal("from.mail"), getVal("username"));
msg.setFrom(fromAddress);
Optional.ofNullable(getVal("to.mail")).ifPresent((String tos) -> {
for (String to : tos.split(";")) {
try {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to, to));
} catch (Exception ex) {
Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
msg.setSubject(parseSubject(getVal("msg.subject")));
msg.setContent(getMessagePart());
return msg;
}
public static void main(String[] args) throws Exception {
final Properties props = new Properties();
props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(props.getProperty("address.sender")));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
message.setSubject("Test JavaMail");
message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");
Transport.send(message);
log.info("Message was sent");
}
@Test
public void testSuccessWithConnectedTransport() throws Exception {
source.setSubject("msg subject");
source.setFrom("[email protected]");
source.setHeader("Header1", "Value1");
BytesMessage message = bytesMessageFor(source, new Address[]{new InternetAddress("[email protected]")});
Transport transport = Mockito.mock(Transport.class);
when(transport.isConnected()).thenReturn(true);
when(sessionDelegate.findTransport(eq("testProto"))).thenReturn(transport);
jms2JavaMail.onMessage(message);
verify(message, times(1)).acknowledge();
verify(transport, never()).connect();
verify(transport, never()).close();
ArgumentCaptor<MimeMessage> mimeMessageArgumentCaptor = ArgumentCaptor.forClass(MimeMessage.class);
ArgumentCaptor<Address[]> addressArgumentCaptor = ArgumentCaptor.forClass(Address[].class);
verify(transport, times(1)).sendMessage(mimeMessageArgumentCaptor.capture(), addressArgumentCaptor.capture());
MimeMessage dst = mimeMessageArgumentCaptor.getValue();
InternetAddress toAddr = (InternetAddress) addressArgumentCaptor.getValue()[0];
Assert.assertEquals("[email protected]", toAddr.getAddress());
Assert.assertEquals(source.getSubject(), dst.getSubject());
Assert.assertArrayEquals(source.getFrom(), dst.getFrom());
Assert.assertArrayEquals(source.getHeader("Header1"), dst.getHeader("Header1"));
verify(javaMailJMSStatistics, times(1)).onSuccess(any(MimeMessage.class), any(Address[].class));
verify(javaMailJMSStatistics, never()).onFailure(any(MimeMessage.class), any(Address[].class), any(Exception.class));
}
@Test
public void testSuccess_withRetry() throws Exception {
IcannReportingUploadAction action = createAction();
when(mockReporter.send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv"))
.thenThrow(new IOException("Expected exception."))
.thenReturn(true);
action.run();
verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-activity-200606.csv");
verify(mockReporter).send(PAYLOAD_FAIL, "tld-activity-200606.csv");
verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-transactions-200606.csv");
verify(mockReporter, times(2)).send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv");
verifyNoMoreInteractions(mockReporter);
verify(emailService)
.sendEmail(
EmailMessage.create(
"ICANN Monthly report upload summary: 3/4 succeeded",
"Report Filename - Upload status:\n"
+ "foo-activity-200606.csv - SUCCESS\n"
+ "tld-activity-200606.csv - FAILURE\n"
+ "foo-transactions-200606.csv - SUCCESS\n"
+ "tld-transactions-200606.csv - SUCCESS",
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]")));
}
public boolean sendMail(String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailProperties.getTo()));
msg.setSubject(subject);
msg.setContent(body, "text/html");
Transport transport = session.getTransport();
transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
transport.sendMessage(msg, msg.getAllRecipients());
return true;
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
return false;
}
private Email createEmailWithEmptyCustomHeaders() throws Exception {
return DefaultEmail.builder()
.from(new InternetAddress("[email protected]"))
.to(null)
.cc(null)
.bcc(null)
.replyTo(new InternetAddress("[email protected]"))
.receiptTo(new InternetAddress("[email protected]"))
.depositionNotificationTo(new InternetAddress("[email protected]"))
.encoding("UTF-16")
.locale(Locale.ITALY)
.sentAt(SEND_AT_DATE)
.subject("subject")
.body("body")
.customHeaders(ImmutableMap.of())
.build();
}
@Test
public void testSuccess_emailOverallInvoice() throws MessagingException {
emailUtils.emailOverallInvoice();
verify(emailService).sendEmail(contentCaptor.capture());
EmailMessage emailMessage = contentCaptor.getValue();
EmailMessage expectedContent =
EmailMessage.newBuilder()
.setFrom(new InternetAddress("[email protected]"))
.setRecipients(
ImmutableList.of(
new InternetAddress("[email protected]"), new InternetAddress("[email protected]")))
.setSubject("Domain Registry invoice data 2017-10")
.setBody("Attached is the 2017-10 invoice for the domain registry.")
.setAttachment(
Attachment.newBuilder()
.setContent("test,data\nhello,world")
.setContentType(MediaType.CSV_UTF_8)
.setFilename("REG-INV-2017-10.csv")
.build())
.build();
assertThat(emailMessage).isEqualTo(expectedContent);
}
/**
* This method resturns only the email address portion of the sender
* contained in the first From header
*
* @return the sender address
* @throws PackageException
*/
@PublicAtsApi
public String getSenderAddress() throws PackageException {
try {
Address[] fromAddresses = message.getFrom();
if (fromAddresses == null || fromAddresses.length == 0) {
throw new PackageException("Sender not present");
}
InternetAddress fromAddress = (InternetAddress) fromAddresses[0];
return fromAddress.getAddress();
} catch (MessagingException me) {
throw new PackageException(me);
}
}
@Test
public void javaMailSenderWithMimeMessage() throws MessagingException {
MockJavaMailSender sender = new MockJavaMailSender();
sender.setHost("host");
sender.setUsername("username");
sender.setPassword("password");
MimeMessage mimeMessage = sender.createMimeMessage();
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
sender.send(mimeMessage);
assertEquals("host", sender.transport.getConnectedHost());
assertEquals("username", sender.transport.getConnectedUsername());
assertEquals("password", sender.transport.getConnectedPassword());
assertTrue(sender.transport.isCloseCalled());
assertEquals(1, sender.transport.getSentMessages().size());
assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
/**
* {@inheritDoc}
*/
public void sendMail(InternetAddress from, InternetAddress[] to, String subject, String content, InternetAddress[] headerTo,
InternetAddress[] replyTo, List<String> additionalHeaders)
{
HashMap<RecipientType, InternetAddress[]> recipients = null;
if (headerTo != null)
{
recipients = new HashMap<RecipientType, InternetAddress[]>();
recipients.put(RecipientType.TO, headerTo);
}
sendMail(from, to, subject, content, recipients, replyTo, additionalHeaders, null);
}
private List<InternetAddress> parseAddress(E event) {
int len = toPatternLayoutList.size();
List<InternetAddress> iaList = new ArrayList<InternetAddress>();
for (int i = 0; i < len; i++) {
try {
PatternLayoutBase<E> emailPL = toPatternLayoutList.get(i);
String emailAdrr = emailPL.doLayout(event);
if ((emailAdrr == null) || (emailAdrr.length() == 0)) {
continue;
}
InternetAddress[] tmp = InternetAddress.parse(emailAdrr, true);
iaList.addAll(Arrays.asList(tmp));
} catch (AddressException e) {
addError("Could not parse email address for ["
+ toPatternLayoutList.get(i) + "] for event [" + event
+ "]", e);
return iaList;
}
}
return iaList;
}
/**
* Building the message needed for sending as an email.
*
* @param subject Email subject
* @return built mime message
* @throws MessagingException if the properties set to the message are not valid
*/
private MimeMessage createBasicMessage(String subject) throws MessagingException {
MimeMessage message = new MimeMessage((Session) null);
message.setFrom(new InternetAddress(FROM_ADDRESS));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
message.setSubject(subject);
message.setText("Content :" + subject);
message.setSentDate(new Date());
return message;
}
@Test
public void shouldPlainTextFormatInternetAddress() throws Exception {
//Arrange
InternetAddress internetAddress = new InternetAddress("[email protected]", "Mr. Test");
//Act
String givenFormattedText = EmailFieldFormat.plainText(internetAddress);
//Assert
assertions.assertThat(givenFormattedText)
.isNotNull()
.isNotEmpty()
.isEqualTo("[email protected]");
}
/**
* Inner method checking if email address is valid.
*
* @param email
* @return
*/
private static boolean isValidEmail(String email) {
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
return true;
} catch (AddressException e) {
return false;
}
}
public String getFrom(Message message) throws MessagingException {
Address from[] = message.getFrom();
if ((from != null) && (from.length > 0) && (from[0] instanceof InternetAddress)) {
return ((InternetAddress)from[0]).getAddress();
}
return null;
}
public void setTo(String[] to) throws MessagingException {
Assert.notNull(to, "To address array must not be null");
InternetAddress[] addresses = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
addresses[i] = parseAddress(to[i]);
}
setTo(addresses);
}
@Override
public void notify(final NotificationContext context, final String subject, final String messageText) throws NotificationFailedException {
final Properties properties = getMailProperties(context);
final Session mailSession = createMailSession(properties);
final Message message = new MimeMessage(mailSession);
try {
message.setFrom(InternetAddress.parse(context.getProperty(FROM).evaluateAttributeExpressions().getValue())[0]);
final InternetAddress[] toAddresses = toInetAddresses(context.getProperty(TO).evaluateAttributeExpressions().getValue());
message.setRecipients(RecipientType.TO, toAddresses);
final InternetAddress[] ccAddresses = toInetAddresses(context.getProperty(CC).evaluateAttributeExpressions().getValue());
message.setRecipients(RecipientType.CC, ccAddresses);
final InternetAddress[] bccAddresses = toInetAddresses(context.getProperty(BCC).evaluateAttributeExpressions().getValue());
message.setRecipients(RecipientType.BCC, bccAddresses);
message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions().getValue());
message.setSubject(subject);
final String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions().getValue();
message.setContent(messageText, contentType);
message.setSentDate(new Date());
Transport.send(message);
} catch (final ProcessException | MessagingException e) {
throw new NotificationFailedException("Failed to send E-mail Notification", e);
}
}
private static SearchTermBuilder createRecipientSearchTermBuilder(final Message.RecipientType type) {
return new SearchTermBuilder() {
@Override
public SearchTerm build() {
try {
return new RecipientTerm(type, new InternetAddress(getParameters().get(0)));
} catch (AddressException e) {
throw new IllegalArgumentException("Address is not correct", e);
}
}
};
}
/**
* Transfer string addresses into java-mail addresses
*
* @param stringAddresses
* @return
* @throws AddressException
*/
private InternetAddress[] transformAdresses(
String[] stringAddresses ) throws AddressException {
List<InternetAddress> mailAddresses = new ArrayList<InternetAddress>();
for (String stringAddress : stringAddresses) {
mailAddresses.add(new InternetAddress(stringAddress));
}
return mailAddresses.toArray(new InternetAddress[mailAddresses.size()]);
}
@Test
public void javaMailSenderWithSimpleMessages() throws MessagingException {
MockJavaMailSender sender = new MockJavaMailSender();
sender.setHost("host");
sender.setUsername("username");
sender.setPassword("password");
SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
simpleMessage1.setTo("[email protected]");
SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
simpleMessage2.setTo("[email protected]");
sender.send(simpleMessage1, simpleMessage2);
assertEquals("host", sender.transport.getConnectedHost());
assertEquals("username", sender.transport.getConnectedUsername());
assertEquals("password", sender.transport.getConnectedPassword());
assertTrue(sender.transport.isCloseCalled());
assertEquals(2, sender.transport.getSentMessages().size());
MimeMessage sentMessage1 = sender.transport.getSentMessage(0);
List<Address> tos1 = Arrays.asList(sentMessage1.getRecipients(Message.RecipientType.TO));
assertEquals(1, tos1.size());
assertEquals("[email protected]", ((InternetAddress) tos1.get(0)).getAddress());
MimeMessage sentMessage2 = sender.transport.getSentMessage(1);
List<Address> tos2 = Arrays.asList(sentMessage2.getRecipients(Message.RecipientType.TO));
assertEquals(1, tos2.size());
assertEquals("[email protected]", ((InternetAddress) tos2.get(0)).getAddress());
}
/**
* Publish post.
*
* @throws MessagingException if an error occurs while publishing.
* @throws IOException if there are problems with reading file with the post text.
*/
public void publish() throws MessagingException, IOException {
final Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", true);
final Session session = Session.getInstance(props, null);
final MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
mimeMessage.setFrom(new InternetAddress(username));
mimeMessage.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(RECIPIENT_ADDRESS));
final String post = new String(Files.readAllBytes(Paths.get(postFilename)),
StandardCharsets.UTF_8);
final BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(post, "text/plain");
final Multipart multipart = new MimeMultipart("alternative");
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
final Transport transport = session.getTransport("smtp");
transport.connect(SMTP_HOST, username, password);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
@Test
public void messageHeaders() throws Exception {
greenMail.setUser("[email protected]", "bpmn");
Session smtpSession = greenMail.getSmtp().createSession();
MimeMessage message = new MimeMessage(smtpSession);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.CC, new InternetAddress("[email protected]"));
message.setSubject("subject");
message.setText("body");
GreenMailUtil.sendMimeMessage(message);
PollMailResponse response = MailConnectors.pollMails()
.createRequest()
.folder("INBOX")
.execute();
List<Mail> mails = response.getMails();
assertThat(mails).hasSize(1);
Mail mail = mails.get(0);
assertThat(mail.getFrom()).isEqualTo("[email protected]");
assertThat(mail.getTo()).isEqualTo("[email protected]");
assertThat(mail.getCc()).isEqualTo("[email protected]");
assertThat(mail.getSubject()).isEqualTo("subject");
assertThat(mail.getSentDate()).isNotNull();
assertThat(mail.getReceivedDate()).isNotNull();
assertThat(mail.getMessageNumber()).isEqualTo(1);
assertThat(mail.getMessageId()).isNotNull();
}