使用javamail发送邮件
使用javamail发送邮件分3个步骤
1.获取Session
2.定义邮件格式及内容
3.发送邮件
代码如下:
1 public void sendMail() {
2
3 Properties props = System.getProperties();
4 props.put("mail.smtp.host", SysConfig.mailhost);
5 props.put("mail.smtp.auth", "true");
6 if (SysConfig.mailhost.equals("smtp.gmail.com")) {
7 props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
8 props.setProperty("mail.smtp.socketFactory.fallback", "false");
9 props.setProperty("mail.smtp.port", "465");
10 props.setProperty("mail.smtp.socketFactory.port", "465");
11 }
12 Transport smtp = null;
13 try {
14 //第一步 获取发送邮件的Session
15 Session session = Session.getDefaultInstance(props, null);
16
17 //第二步 定义邮件的格式及内容
18 MimeMessage message = new MimeMessage(session);
19 message.setFrom(new InternetAddress(SysConfig.mailfrom));
20 message.addRecipient(Message.RecipientType.TO, new InternetAddress(
21 SysConfig.mailto));
22 message.setSubject("测试邮件");
23 message.setContent("测试正文", "text/html;charset=utf-8");
24
25 //第三部 发送邮件
26 smtp = session.getTransport("smtp");
27
28 smtp.connect(SysConfig.mailhost, SysConfig.mailfrom, SysConfig.mailpassword);
29 smtp.sendMessage(message, message.getAllRecipients());
30
31 } catch (AddressException e) {
32 System.out.println(e.getMessage());
33 } catch (MessagingException e) {
34 System.out.println(e.getMessage());
35 } finally {
36 try {
37 smtp.close();
38 } catch (MessagingException e) {
39 System.out.println(e.getMessage());
40 }
41 }
42 }
在代码中需要定义4个变量
mailhost为发送邮箱的smtp
mailfrom为发送邮箱地址
mailpassword为发送邮箱密码
mailto为接收邮箱地址
在第二步定义邮件格式中可以通过message.addRecipient添加多个接收地址