下面列出了怎么用javax.mail.Message.RecipientType的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void sendSimpleSpittleEmail() throws Exception {
Spitter spitter = new Spitter(1L, "habuma", null, "Craig Walls", "[email protected]", true);
Spittle spittle = new Spittle(1L, spitter, "Hiya!", new Date());
mailService.sendSimpleSpittleEmail("[email protected]", spittle);
MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
assertEquals("Craig Walls says: Hiya!", ((String) receivedMessages[0].getContent()).trim());
Address[] from = receivedMessages[0].getFrom();
assertEquals(1, from.length);
assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
assertEquals("[email protected]",
((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());
}
public void receiveTest() throws Exception {
MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
Address[] from = receivedMessages[0].getFrom();
assertEquals(1, from.length);
assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
assertEquals(toEmail,
((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());
MimeMultipart multipart = (MimeMultipart) receivedMessages[0].getContent();
Part part = null;
for(int i=0;i<multipart.getCount();i++) {
part = multipart.getBodyPart(i);
System.out.println(part.getFileName());
System.out.println(part.getSize());
}
}
/** {@inheritDoc} */
public void send() {
try {
Address[] addrs = message.getRecipients(RecipientType.TO);
if (addrs == null || addrs.length == 0) {
log.warn("Aborting mail message " + message.getSubject() +
": No recipients");
return;
}
Transport.send(message);
}
catch (MessagingException me) {
String msg = "MessagingException while trying to send email: " +
me.toString();
log.warn(msg);
throw new JavaMailException(msg, me);
}
}
/**
* Private helper method to do the heavy lifting of setting the recipients field for
* a message
* @param type The javax.mail.Message.RecipientType (To, CC, or BCC) for the recipients
* @param recipIn A string array of email addresses
*/
private void setRecipients(RecipientType type, String[] recipIn) {
log.debug("setRecipients called.");
Address[] recAddr = null;
try {
List tmp = new LinkedList();
for (int i = 0; i < recipIn.length; i++) {
InternetAddress addr = new InternetAddress(recipIn[i]);
log.debug("checking: " + addr.getAddress());
if (verifyAddress(addr)) {
log.debug("Address verified. Adding: " + addr.getAddress());
tmp.add(addr);
}
}
recAddr = new Address[tmp.size()];
tmp.toArray(recAddr);
message.setRecipients(type, recAddr);
}
catch (MessagingException me) {
String msg = "MessagingException while trying to send email: " +
me.toString();
log.warn(msg);
throw new JavaMailException(msg, me);
}
}
public void deliverMultipartMessage(String user, String password, String from, String subject,
String contentType, Object body) throws Exception {
GreenMailUser greenUser = greenMail.setUser(user, password);
MimeMultipart multiPart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
multiPart.addBodyPart(textPart);
textPart.setContent(body, contentType);
Session session = GreenMailUtil.getSession(server.getServerSetup());
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
mimeMessage.setFrom(from);
mimeMessage.setSubject(subject);
mimeMessage.setContent(multiPart, "multipart/mixed");
greenUser.deliver(mimeMessage);
}
public boolean sendMsg(String recipient, String subject, String content)
throws MessagingException {
// Create a mail object
Session session = Session.getInstance(props, new Authenticator() {
// Set the account information session,transport will send mail
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
}
});
session.setDebug(true);
Message msg = new MimeMessage(session);
try {
msg.setSubject(subject); //Set the mail subject
msg.setContent(content,"text/html;charset=utf-8");
msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME)); //Set the sender
msg.setRecipient(RecipientType.TO, new InternetAddress(recipient)); //Set the recipient
Transport.send(msg);
return true;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
return false;
}
}
public static Mail from(Message message) throws MessagingException, IOException {
Mail mail = new Mail();
mail.from = InternetAddress.toString(message.getFrom());
mail.to = InternetAddress.toString(message.getRecipients(RecipientType.TO));
mail.cc = InternetAddress.toString(message.getRecipients(RecipientType.CC));
mail.subject = message.getSubject();
mail.sentDate = message.getSentDate();
mail.receivedDate = message.getReceivedDate();
mail.messageNumber = message.getMessageNumber();
if (message instanceof MimeMessage) {
MimeMessage mimeMessage = (MimeMessage) message;
// extract more informations
mail.messageId = mimeMessage.getMessageID();
}
processMessageContent(message, mail);
return mail;
}
protected Message createMessage(SendMailRequest request, Session session) throws Exception {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getFrom(), request.getFromAlias()));
message.setRecipients(RecipientType.TO, InternetAddress.parse(request.getTo()));
if (request.getCc() != null) {
message.setRecipients(RecipientType.CC, InternetAddress.parse(request.getCc()));
}
if (request.getBcc() != null) {
message.setRecipients(RecipientType.BCC, InternetAddress.parse(request.getBcc()));
}
message.setSentDate(new Date());
message.setSubject(request.getSubject());
if (hasContent(request)) {
createMessageContent(message, request);
} else {
message.setText("");
}
return message;
}
@Test
public void messageWithCc() throws MessagingException {
MailConnectors.sendMail()
.createRequest()
.from("test")
.to("[email protected]")
.cc("[email protected]")
.subject("subject")
.execute();
MimeMessage[] mails = greenMail.getReceivedMessages();
assertThat(mails).hasSize(2);
assertThat(mails[0].getRecipients(RecipientType.CC))
.hasSize(1)
.extracting("address").contains("[email protected]");
}
@Test
public void messageWithBcc() throws MessagingException {
MailConnectors.sendMail()
.createRequest()
.from("test")
.to("[email protected]")
.bcc("[email protected]")
.subject("subject")
.execute();
MimeMessage[] mails = greenMail.getReceivedMessages();
assertThat(mails).hasSize(2);
assertThat(mails[0].getRecipients(RecipientType.TO))
.hasSize(1)
.extracting("address").contains("[email protected]");
assertThat(mails[0].getRecipients(RecipientType.BCC)).isNull();
}
@Test
public void testSuccess_simple() throws Exception {
EmailMessage content = createBuilder().build();
sendEmailService.sendEmail(content);
Message message = getMessage();
assertThat(message.getAllRecipients())
.asList()
.containsExactly(new InternetAddress("[email protected]"));
assertThat(message.getFrom())
.asList()
.containsExactly(new InternetAddress("[email protected]"));
assertThat(message.getRecipients(RecipientType.BCC)).isNull();
assertThat(message.getSubject()).isEqualTo("Subject");
assertThat(message.getContentType()).startsWith("multipart/mixed");
assertThat(getInternalContent(message).getContent().toString()).isEqualTo("body");
assertThat(getInternalContent(message).getContentType()).isEqualTo("text/plain; charset=utf-8");
assertThat(((MimeMultipart) message.getContent()).getCount()).isEqualTo(1);
}
@Test
public void testSuccess_bcc() throws Exception {
EmailMessage content =
createBuilder()
.setBccs(
ImmutableList.of(
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]")))
.build();
sendEmailService.sendEmail(content);
Message message = getMessage();
assertThat(message.getRecipients(RecipientType.BCC))
.asList()
.containsExactly(
new InternetAddress("[email protected]"), new InternetAddress("[email protected]"));
}
/**
* Address message.
*
* @param msg message, may not be null.
* @throws MessagingException thrown if error addressing message.
*/
private final void addressMessage(final Message msg) throws MessagingException {
if (from != null) {
msg.setFrom(getAddress(from));
} else {
msg.setFrom();
}
if (to != null && !to.isEmpty()) {
msg.setRecipients(RecipientType.TO, parseAddress(to));
}
//Add CC recipients if defined.
if (cc != null && !cc.isEmpty()) {
msg.setRecipients(RecipientType.CC, parseAddress(cc));
}
//Add BCC recipients if defined.
if (bcc != null && !bcc.isEmpty()) {
msg.setRecipients(RecipientType.BCC, parseAddress(bcc));
}
}
@Test
public void testAddMessages() throws Exception {
final MockMailbox mb = MockMailbox.get("[email protected]");
final MailboxFolder mf = mb.getInbox();
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
mf.add(msg);
Assert.assertEquals(1, mf.getMessageCount());
Assert.assertNotNull(mf.getByMsgNum(1));
Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(1).getSubject());
mf.add(msg);
mf.add(msg);
Assert.assertEquals(3, mf.getMessageCount());
Assert.assertNotNull(mf.getByMsgNum(3));
Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(3).getSubject());
}
@Test(expected = MockTestException.class)
public void testMockMessagesReadonly() throws Exception {
final MockMailbox mb = MockMailbox.get("[email protected]");
final MailboxFolder mf = mb.getInbox();
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
mf.add(msg);
try {
mf.getByMsgNum(1).setHeader("test", "test");
} catch (final IllegalWriteException e) {
throw new MockTestException(e);
}
}
@Test
public void testUIDMessages() throws Exception {
final MockMailbox mb = MockMailbox.get("[email protected]");
final MailboxFolder mf = mb.getInbox();
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
mf.add(msg);
mf.add(msg);
mf.add(msg);
Assert.assertTrue(mf.getUID(mf.getByMsgNum(3)) > 0);
Assert.assertNotNull(mf.getById(mf.getUID(mf.getByMsgNum(3))));
}
@Test
public void test2SendMessage2() throws Exception {
final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true));
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test 1");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });
final Store store = session.getStore("mock_pop3");
store.connect("[email protected]", null);
final Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Assert.assertEquals(1, inbox.getMessageCount());
Assert.assertNotNull(inbox.getMessage(1));
Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
inbox.close(false);
}
@Test
public void test3SendMessage() throws Exception {
Session.getDefaultInstance(getProperties());
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test 1");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
Transport.send(msg);
final Store store = session.getStore("mock_pop3");
store.connect("[email protected]", null);
final Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Assert.assertEquals(1, inbox.getMessageCount());
Assert.assertNotNull(inbox.getMessage(1));
Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
inbox.close(false);
}
/** {@inheritDoc} */
public void send() {
try {
Address[] addrs = message.getRecipients(RecipientType.TO);
if (addrs == null || addrs.length == 0) {
log.warn("Aborting mail message " + message.getSubject() +
": No recipients");
return;
}
Transport.send(message);
}
catch (MessagingException me) {
String msg = "MessagingException while trying to send email: " +
me.toString();
log.warn(msg);
throw new JavaMailException(msg, me);
}
}
/**
* Private helper method to do the heavy lifting of setting the recipients field for
* a message
* @param type The javax.mail.Message.RecipientType (To, CC, or BCC) for the recipients
* @param recipIn A string array of email addresses
*/
private void setRecipients(RecipientType type, String[] recipIn) {
log.debug("setRecipients called.");
Address[] recAddr = null;
try {
List tmp = new LinkedList();
for (int i = 0; i < recipIn.length; i++) {
InternetAddress addr = new InternetAddress(recipIn[i]);
log.debug("checking: " + addr.getAddress());
if (verifyAddress(addr)) {
log.debug("Address verified. Adding: " + addr.getAddress());
tmp.add(addr);
}
}
recAddr = new Address[tmp.size()];
tmp.toArray(recAddr);
message.setRecipients(type, recAddr);
}
catch (MessagingException me) {
String msg = "MessagingException while trying to send email: " +
me.toString();
log.warn(msg);
throw new JavaMailException(msg, me);
}
}
@Override
public void MessagesReceived(Collection<InboundMessage> msgList) throws Exception
{
for (InboundMessage im : msgList)
{
Message msg = new MimeMessage(this.mailSession);
msg.setFrom();
msg.addRecipient(RecipientType.TO, new InternetAddress(getProperty("to")));
msg.setSubject(updateTemplateString(this.messageSubject, im));
if (this.messageBody != null)
{
msg.setText(updateTemplateString(this.messageBody, im));
}
else
{
msg.setText(im.toString());
}
msg.setSentDate(im.getDate());
Transport.send(msg);
}
}
/**
* 发送邮件
*
* @param recipient
* 收件人邮箱地址
* @param subject
* 邮件主题
* @param content
* 邮件内容
* @throws AddressException
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void send(String recipient, String subject, Object content)
throws AddressException, MessagingException, UnsupportedEncodingException {
// 创建mime类型邮件
final MimeMessage message = new MimeMessage(session);
if(authenticator!=null && authenticator.getUsername().indexOf("@") >0){
// 设置发信人
message.setFrom(new InternetAddress(authenticator.getUsername()));
}
if(this.fromEmail!=null){
message.setFrom(new InternetAddress(this.fromEmail));
}
// 设置收件人
String[] toUsers = recipient.split("[\n,;]") ;
InternetAddress[] internetAddress = new InternetAddress[toUsers.length] ;
for(int i=0 ; i<toUsers.length ; i++){
internetAddress[i] = new InternetAddress(toUsers[i]) ;
}
message.setRecipients(RecipientType.TO, internetAddress);
// 设置主题
// message.setSubject(subject);
message.setSubject(MimeUtility.encodeText(subject,"UTF-8","B"));
// 设置邮件内容
message.setContent(content.toString(), "text/html;charset=utf-8");
// 发送
Transport.send(message);
}
/**
* 群发邮件
*
* @param recipients
* 收件人们
* @param subject
* 主题
* @param content
* 内容
* @throws AddressException
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void send(List<String> recipients, String subject, Object content)
throws AddressException, MessagingException, UnsupportedEncodingException {
// 创建mime类型邮件
final MimeMessage message = new MimeMessage(session);
if(authenticator!=null && authenticator.getUsername().indexOf("@") >0){
// 设置发信人
message.setFrom(new InternetAddress(authenticator.getUsername()));
}
if(this.fromEmail!=null){
message.setFrom(new InternetAddress(MimeUtility.encodeText(this.fromEmail, "UTF-8", "B"))+" <"+authenticator.getUsername()+">");
}
// 设置收件人们
final int num = recipients.size();
InternetAddress[] addresses = new InternetAddress[num];
for (int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(RecipientType.TO, addresses);
// 设置主题
// message.setSubject(subject);
//邮件标题处理,防止乱码
message.setSubject(MimeUtility.encodeText(subject,"UTF-8","B"));
// 设置邮件内容
message.setContent(content.toString(), "text/html;charset=utf-8");
// 发送
Transport.send(message);
}
@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 EMailMessageModel createMessageModel(Message msg) throws MessagingException, IOException {
EMailMessageModel model = new EMailMessageModel();
model.setFrom(msg.getFrom()[0].toString());
model.setTo(msg.getRecipients(RecipientType.TO)[0].toString());
model.setSubject(msg.getSubject());
model.setContent(msg.getContent());
return model;
}
@Test
public void messageHeader() throws MessagingException {
MailConnectors.sendMail()
.createRequest()
.from("test")
.fromAlias("me")
.to("[email protected]")
.subject("subject")
.execute();
MimeMessage[] mails = greenMail.getReceivedMessages();
assertThat(mails).hasSize(1);
MimeMessage mail = mails[0];
assertThat(mail.getFrom())
.hasSize(1)
.extracting("address", "personal").contains(tuple("test", "me"));
assertThat(mail.getRecipients(RecipientType.TO))
.hasSize(1)
.extracting("address").contains("[email protected]");
assertThat(mail.getSubject()).isEqualTo("subject");
assertThat(mail.getSentDate()).isNotNull();
}
public static void Send(String to, String subject, String messageText) throws MessagingException{
LOGGER.info("Create a session object");
//Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
//compose the message
try{
LOGGER.info("Create message...");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(RecipientType.TO ,new InternetAddress(to));
message.setSubject(subject);
message.setText(messageText);
// Send message
LOGGER.info("send message...");
Transport transport = session.getTransport("smtps");
transport.connect(host, from, password);
transport.sendMessage(message, message.getAllRecipients());
LOGGER.info("Message sent successfully...");
} catch (MessagingException mex) {
LOGGER.severe("Message cannot be sent: " + mex.getMessage());
throw mex;
}
}
public RecipientGroup tryAddTo(String toEmail){
if( ! hasText(toEmail)) return this;
if( ! toEmail.contains("@")) return this;
toEmail = toEmail.trim();
try {
putToListMap(byType, RecipientType.TO, new InternetAddress(toEmail));
}catch(Exception e){
//ok
}
return this;
}
private static void assertHeaders(ExpectedEmailHeader expectedEmail, Message actualEmail, AssertionRegistry assertions) throws MessagingException {
Address[] from = actualEmail == null || actualEmail.getFrom() == null ? null : actualEmail.getFrom();
assertions.register(() -> Assert.assertEquals("subject should be '" + expectedEmail.getSubject() + "'", expectedEmail.getSubject(), actualEmail == null ? null : actualEmail.getSubject()));
assertions.register(() -> Assert.assertEquals("should have only one from", (Integer) 1, from == null ? null : from.length));
assertions.register(() -> Assert.assertEquals("from should be '" + expectedEmail.getFrom() + "'", expectedEmail.getFrom(), from == null ? null : from[0].toString()));
int recipients = expectedEmail.getTo().size() + expectedEmail.getBcc().size() + expectedEmail.getCc().size();
assertions.register(() -> Assert.assertEquals("should be received by " + recipients + " recipients", (Integer) recipients,
actualEmail == null || actualEmail.getAllRecipients() == null ? null : actualEmail.getAllRecipients().length));
assertRecipients(expectedEmail.getTo(), actualEmail, RecipientType.TO, assertions);
assertRecipients(expectedEmail.getCc(), actualEmail, RecipientType.CC, assertions);
assertRecipients(expectedEmail.getBcc(), actualEmail, RecipientType.BCC, assertions);
}
private static void assertRecipients(List<String> expectedRecipients, Message actualEmail, RecipientType recipientType, AssertionRegistry assertions) throws MessagingException {
Address[] actualRecipients = actualEmail == null ? null : actualEmail.getRecipients(recipientType);
if (expectedRecipients.isEmpty()) {
assertions.register(() -> Assert.assertTrue("should be received by no recipients (of type RecipientType." + recipientType + ")", actualRecipients == null || actualRecipients.length == 0));
} else {
assertions.register(() -> Assert.assertEquals("should be received by " + expectedRecipients.size() + " recipients (of type RecipientType." + recipientType + ")",
(Integer) expectedRecipients.size(), actualRecipients == null ? null : actualRecipients.length));
for (int i = 0; i < expectedRecipients.size(); i++) {
final int idx = i;
assertions.register(() -> Assert.assertEquals("recipient " + recipientType + "[" + idx + "] should be '" + expectedRecipients.get(idx) + "'", expectedRecipients.get(idx),
actualRecipients != null && idx < actualRecipients.length ? actualRecipients[idx].toString() : null));
}
}
}