MailUtils 测试邮件是否发送

 1 import java.util.Properties;
 2 
 3 import javax.mail.Message;
 4 import javax.mail.Session;
 5 import javax.mail.Transport;
 6 import javax.mail.internet.InternetAddress;
 7 import javax.mail.internet.MimeMessage;
 8 import javax.mail.internet.MimeMessage.RecipientType;
 9 
10 public class MailUtils {
11     private static String smtp_host = "smtp.126.com"; 
12     private static String username = "itcast_server@126.com"; 
13     private static String password = "147963qP"; 
14 
15     private static String from = "itcast_server@126.com"; // 使用当前账户
16     public static String activeUrl = "http://localhost:8082/bos_fore/customerAction_activeMail";
17 
18     public static void sendMail(String subject, String content, String to) {
19         Properties props = new Properties();
20         props.setProperty("mail.smtp.host", smtp_host);
21         props.setProperty("mail.transport.protocol", "smtp");
22         props.setProperty("mail.smtp.auth", "true");
23         Session session = Session.getInstance(props);
24         Message message = new MimeMessage(session);
25         try {
26             message.setFrom(new InternetAddress(from));
27             message.setRecipient(RecipientType.TO, new InternetAddress(to));
28             message.setSubject(subject);
29             message.setContent(content, "text/html;charset=utf-8");
30             Transport transport = session.getTransport();
31             transport.connect(smtp_host, username, password);
32             transport.sendMessage(message, message.getAllRecipients());
33         } catch (Exception e) {
34             e.printStackTrace();
35             throw new RuntimeException("邮件发送失败...");
36         }
37     }
38 
39     public static void main(String[] args) {
40         sendMail("测试邮件", "你好,大神", "itcast_search@163.com");
41     }
42 }

 

posted @ 2017-12-12 23:15  龙芳伟  阅读(640)  评论(0编辑  收藏  举报