28 * @paramuserName
29 * 发件人用户名,如:qmail、20082345
30 * @parampassword
31 * 发件人密码
32 * @paramtoAddress
33 * 收件人邮箱地址,如:200712345@qq.com
34 */
35 publicEmailEntity(String fromDomin, String userName, String password) {
36 Properties p = newProperties();
37 //设置邮件发送服务器的地址
38 p.setProperty("mail.host", "smtp." + fromDomin);
39 //设置使用权限验证
40 p.setProperty("mail.smtp.auth", "true");
41 //设置用户身份验证凭据
42 Session ses = Session.getDefaultInstance(p, newMyAuthentic
ator(userName, password));
43 //ses.setDebug(true);//设置是否出现回显信息
44 //创建邮件实体
45 msg = newMimeMessage(ses);
46 try{
47 //设置发件人邮箱地址
48 msg.setFrom(newInternetAddress(userName + "@" + fromDomin));
49 } catch(AddressException e) {
50 e.printStackTrace();
51 } catch(MessagingException e) {
52 e.printStackTrace();
53 }
54 }
55
56 /**
57 * 发送消息
58 *
59 * @paramtitle
60 * 邮件标题
61 * @paramcontent
62 * 邮件正文
63 * @paramtype
64 * 正文的类型,如:text/html、text/plain
65 * @return
66 */
67 publicbooleansendMessage(String toAddress, String title, String content, String type) {
68
69 try{
70 //设置发件人邮箱地址
71 msg.setRecipient(RecipientType.TO, newInternetAddress
(toAddress));
72 //设置邮件发送日期
73 msg.setSentDate(newDate());
74 //设置邮件标题
75 msg.setSubject(title);
76 //设置邮件正文
77 msg.setContent(content, type);
78 //开始发送邮件
79 Transport.send(msg);
80 returntrue;
81 } catch(MessagingException ex) {
82 ex.printStackTrace();
83 returnfalse;
84 }
85 }
86
87 /**
88 * 发送带附件的邮件
89 * @paramtoAddress 收件人的邮箱地址,如suxibo@126.com
90 * @paramtitle 邮件标题
91 * @paramcontent 邮件正文,包括附件
92 * @paramtype 邮件正文的类型
93 * @return
94 */
95 publicbooleansendEmailWithAttachment(String toAddress, String title, MimeMultipart content, String type) {
96 try{
97 msg.setRecipient(RecipientType.TO, newInternetAddress(toAddress));
98 msg.setSentDate(newDate());
99 msg.setSubject(title);
100 msg.setContent(content);
101 Transport.send(msg);
102 returntrue;
103 } catch(MessagingException ex) {
104 ex.printStackTrace();
105 returnfalse;
106 }
107 }
108}
109
110//用户身份验证凭据类
111classMyAuthenticator extendsAuthenticator {
112
113 privateString _userName;
114 privateString _password;
115
116 publicMyAuthenticator(String userName,String password){
117 this._userName = userName;
118 this._password = password;
119 }
120
121 @Override
122 publicPasswordAuthentication getPasswordAuthentication() {
123 //返回使用了用户名和密码的身份验证凭据
124 returnnewPasswordAuthentication(_userName, _password);
125 }
126}