使用jakarta mail发送邮件

介绍如何使用jakarta mail发送邮件

引入jar

1
implementation 'com.sun.mail:jakarta.mail:2.0.1'

sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class Main {
public static void main(String[] args) throws MessagingException {
String to = "to@efg.com";
String from = "from@abc.com";
final String username = "from@abc.com";
final String password = "password";
String host = "smtp-relay.gmail.com"; //使用gmail relay发送邮件

Properties props = getProperties(host);
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Here comes Jakarta Mail!");
//message.setText("Just discovered that Jakarta Mail is fun and easy to use");
//message.setContent("<html><body><h1>test</h1><hr>this is just a test</body></html>", "text/html; charset=utf-8");

Multipart mp = new MimeMultipart();

String html = """
<html>
<body>
<h1>test</h1>
<hr>this is just a test
<hr><img src='cid:my-image-id'>
<hr>footer
</body>
</html>
""";
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html; charset=utf-8");
mp.addBodyPart(htmlPart);

MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(new FileDataSource("/Users/gikeihi/Downloads/025.png")));
imagePart.setHeader("Content-ID", "<my-image-id>");
mp.addBodyPart(imagePart);

message.setContent(mp);

Transport.send(message);
System.out.println("Email Message Sent Successfully");
}

private static Properties getProperties(String host) {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.localhost", "abc.com"); //这个地方不设的的话,如果默认为localhost,gmail会发送失败
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
return props;
}
}

讨论

即使设定完全正确,由于网络,以及smtp服务器的限制等原因,总是有失败的时候。
为了保证程序的健壮性,需要对异常情况进行处理。

  • 处理发信client和smtp服务器件的错误
    一定要catch住发送的异常,并记录在案,然后做重发的机制。
  • 监控smtp投递情况
    及时发给smtp是成功的,也很难保证smtp服务能及时正确的投递了邮件,所以最好每封信都bcc一个监控邮件地址,这样能更好的监控哪些邮件,什么时候,投递给谁了。
  • 监控对方拒收
    一般对方拒收的话,发信邮件地址里会接收到错误邮件,通过监控这些邮件,可以知道发给谁的邮件投递失败了。
  • 垃圾邮件
    很遗憾的是,如果发送的邮件最终被对方判定为垃圾邮件,这时候是没有任何手段可以监控的到的。