使用java发送邮件

先上代码,稍后解释

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
/**
* Send e-mail using 163 mail
*
* @param hardInfo
* @throws AddressException
* @throws MessagingException
* @throws IOException
*/
public static void sendEmail()
throws AddressException, MessagingException, IOException {
Properties props = new Properties();
props.setProperty("mail.host", "smtp.126.com"); // Set email protocol, 'cause I use 163 mail
props.setProperty("mail.smtp.auth", "true"); // If do verification

Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Mail Username", "Password");
}
};
Session session = Session.getInstance(props, auth);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("EmailAddress"));
msg.setRecipients(RecipientType.TO, "receive user");

msg.setSubject("Mail Subject");

MimeMultipart list = new MimeMultipart();
MimeBodyPart part1 = new MimeBodyPart();

part1.setContent("Mail Message body", "Code style, for example text/html;charset=utf-8"); // You should write "<br>" when you use text/html

list.addBodyPart(part1);
MimeBodyPart part2 = new MimeBodyPart();
part2.attachFile("filepathname"); // Set Attach file
list.addBodyPart(part2); // Add attach file
msg.setContent(list);
Transport transport = session.getTransport("smtp"); // Set protocol
transport.connect("From address", "Mail authorization code ");
transport.sendMessage(msg, msg.getAllRecipients());
}

解释

  1. 发送基本上就是这样发送的,因为我们使用的smtp协议,网易邮箱为了保证一些方面的安全性,现在开启smtp使用协议必须要获取授权码,添加授权码的地方在倒数第二行。
  2. 邮件的内容使用字符串,如果你后面写的文本格式是 text/html 的话,如果要进行正文换行的话,需要使用html中的换行符号<br>来进行换行
  3. 在一开始一定要写上使用的邮箱协议,否则会出现连接失败