你的位置:首页 > 软件开发 > Java > 邮件功能开发

邮件功能开发

发布时间:2012-03-06 23:00:20
本节摘要:本节主要简单介绍一下javamail插件的使用引入:最近项目中要做一个简单的邮件功能,即从前台输入邮件内容,去配置文件中读取发件人、收件人等信息后,然后发送邮件到指定的邮箱,其中收件人和抄送人可以有多个,基于这个需求,查询了相关资料,决定采用javamail这个插件来实现。preparation:1.JavaMail的介绍 JavaMail,顾名思义,提供给开发者 ...

邮件功能开发

本节摘要:本节主要简单介绍一下javamail插件的使用

引入:最近项目中要做一个简单的邮件功能,即从前台输入邮件内容,去配置文件中读取发件人、收件人等信息后,然后发送邮件到指定的邮箱,其中收件人和抄送人可以有多个,基于这个需求,查询了相关资料,决定采用javamail这个插件来实现。

preparation:

1.JavaMail的介绍

     JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。

   虽然JavaMail是Sun的API之一,但它目前还没有被加在标准的java开发工具包中(Java Development Kit),这就意味着你在使用前必须另外下载JavaMail文件。除此以外,你还需要有Sun的JavaBeans Activation Framework (JAF)。JavaBeans Activation Framework的运行很复杂,在这里简单的说就是JavaMail的运行必须得依赖于它的支持。在Windows 2000下使用需要指定这些文件的路径,在其它的操作系统上也类似。

   JavaMail是可选包,因此如果需要使用的话你需要首先从java.sun.com下载。目前最新版本是JavaMail1.4,使用JavaMail的时候需要Javabean Activation Framework的支持,因此你也需要下载JAF。安装JavaMail只是需要把他们加入到CLASSPATH中去,如果你不想修改CLASSPATH的话,可以直接把他们的jar包直接copy到JAVA_HOME/lib/ext下。这样JavaMail就安装好了。   JavaMail包中用于处理电子邮件的核心类是:Session,Message,Address,Authenticator,Transport,Store,Folder等。Session定义了一个基本的邮件会话,它需要从Properties中读取类似于邮件服务器,用户名和密码等信息 

2.下载jar包

网上有下载链接,但是这里我还是把jar包给上传

javamail-1[1].4.2.zip

jaf-1_1_1.zip

dom4j.jar 这个jar就不提供下载资源了

 

3.项目环境

system:win7  myeclipse:6.5  tomcat:5.0 JDK:编译和运行都是1.4

邮件功能开发

为了方便,还是在之前的UpDown项目下运行的,本次用到的文件只有sendmail包下的文件。

 

4.class&method

请参考:http://www.jspcn.net/htmlnews/1150019680500144.html

 

start

导入javamail、JAF、dom4j的jar包,然后新建对应的文件如下:

Encrypt.jar  主要是用于对密码进行加密和解密

邮件功能开发邮件功能开发Encrypt.java
 1 package sendmail;
2
3 /**
4 * Module: Encrypt.java
5 * Description: 对密码进行加密和解密
6 * Company:
7 * Author: ptp
8 * Date: Mar 6, 2012
9 */
10 public class Encrypt
11 {
12
13 public static final int pass1 = 10;
14 public static final int pass2 = 1;
15
16 public Encrypt()
17 {
18 }
19
20 /**
21 * @Title: DoEncrypt
22 * @Description: 对密码进行加密的方法
23 * @param @param str
24 * @param @return 设定文件
25 * @return String 返回类型
26 * @throws
27 */
28 public static String DoEncrypt(String str)
29 {
30 StringBuffer enStrBuff = new StringBuffer();
31 for (int i = 0; i < str.length(); i++)
32 {
33 int tmpch = str.charAt(i);
34 tmpch ^= 1;
35 tmpch ^= 0xa;
36 enStrBuff.append(Integer.toHexString(tmpch));
37 }
38
39 return enStrBuff.toString().toUpperCase();
40 }
41
42 /**
43 * @Title: DoDecrypt
44 * @Description: 对密码进行解密的方法
45 * @param @param str
46 * @param @return 设定文件
47 * @return String 返回类型
48 * @throws
49 */
50 public static String DoDecrypt(String str)
51 {
52 String deStr = str.toLowerCase();
53 StringBuffer deStrBuff = new StringBuffer();
54 for (int i = 0; i < deStr.length(); i += 2)
55 {
56 String subStr = deStr.substring(i, i + 2);
57 int tmpch = Integer.parseInt(subStr, 16);
58 tmpch ^= 1;
59 tmpch ^= 0xa;
60 deStrBuff.append((char)tmpch);
61 }
62
63 return deStrBuff.toString();
64 }
65
66 public static void main(String args[])
67 {
68 String source = "123456";
69 String s = DoEncrypt(source);
70 System.out.println("de=" + s);
71
72 source = DoDecrypt(s);
73 System.out.println("en=" + source);
74
75 }
76 }

 

MailInfo.java javabean定义邮件需要的字段以及对应的get和set方法

邮件功能开发邮件功能开发MailInfo.java
 1 package sendmail;
2
3 /**
4 *Module: MailInfo.java
5 *Description: 定义发送邮件的所有字段的javabean
6 *Company:
7 *Author: ptp
8 *Date: Mar 1, 2012
9 */
10 public class MailInfo{
11 private String host;// 邮件服务器域名或IP
12 private String from;// 发件人
13 private String to;// 收件人
14 private String cc;// 抄送人
15 private String username;// 发件人用户名
16 private String password;// 发件人密码
17 private String title;// 邮件的主题
18 private String content;// 邮件的内容
19
20 public String getHost() {
21 return host;
22 }
23 public void setHost(String host) {
24 this.host = host;
25 }
26 public String getFrom() {
27 return from;
28 }
29 public void setFrom(String from) {
30 this.from = from;
31 }
32 public String getTo() {
33 return to;
34 }
35 public void setTo(String to) {
36 this.to = to;
37 }
38 public String getCc() {
39 return cc;
40 }
41 public void setCc(String cc) {
42 this.cc = cc;
43 }
44 public String getUsername() {
45 return username;
46 }
47 public void setUsername(String username) {
48 this.username = username;
49 }
50 public String getPassword() {
51 return password;
52 }
53 public void setPassword(String password) {
54 this.password = password;
55 }
56 public String getTitle() {
57 return title;
58 }
59 public void setTitle(String title) {
60 this.title = title;
61 }
62 public String getContent() {
63 return content;
64 }
65 public void setContent(String content) {
66 this.content = content;
67 }
68
69 }

 

MyAuthenticator.java 用于对邮件授权

邮件功能开发邮件功能开发MyAuthenticator.java
 1 package sendmail;
2
3 /**
4 *Module: MailInfo.java
5 *Description: 邮件授权类
6 *Company:
7 *Author: ptp
8 *Date: Mar 6, 2012
9 */
10 import javax.mail.PasswordAuthentication;
11
12 public class MyAuthenticator extends javax.mail.Authenticator {
13 private String strUser;
14 private String strPwd;
15
16 public MyAuthenticator(String user, String password) {
17 this.strUser = user;
18 this.strPwd = password;
19 }
20
21 protected PasswordAuthentication getPasswordAuthentication() {
22 return new PasswordAuthentication(strUser, strPwd);
23 }
24 }

 

SendMail.java 发送邮件的封装类

 先读取邮件功能开发邮件功能开发SendMail.java

  1 package sendmail;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.io.UnsupportedEncodingException;
10 import java.util.Properties;
11 import javax.mail.Message;
12 import javax.mail.MessagingException;
13 import javax.mail.Session;
14 import javax.mail.Transport;
15 import javax.mail.internet.AddressException;
16 import javax.mail.internet.InternetAddress;
17 import javax.mail.internet.MimeMessage;
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20 import org.dom4j.Document;
21 import org.dom4j.DocumentException;
22 import org.dom4j.DocumentHelper;
23 import org.dom4j.Element;
24
25 /**
26 * Module: SendMail.java
27 * Description: 发送邮件
28 * Company:
29 * Author: ptp
30 * Date: Mar 1, 2012
31 */
32
33 public class SendMail {
34
35 private static final Log log = LogFactory.getLog(SendMail.class);
36
37 // 配置文件
38 private final static String 39 + File.separator + "SendMail. 40
41 //
42 private static MailInfo mailInfo = new MailInfo();
43
44 /**
45 * <p>Title: read 46 * <p>Description:读取 47 * @param 48 * @return
49 * @throws Exception
50 */
51 private String readthrows Exception {
52 log.debug(" 53
54 String fileContent = "";
55 File file = new File( 56 if (file.isFile() && file.exists()) {
57 try {
58 InputStreamReader read = new InputStreamReader(
59 new FileInputStream(file), "UTF-8");
60 BufferedReader reader = new BufferedReader(read);
61 String line;
62 try {
63 while ((line = reader.readLine()) != null) {
64 fileContent += line;
65 }
66 reader.close();
67 read.close();
68 } catch (IOException e) {
69 e.printStackTrace();
70 }
71 } catch (UnsupportedEncodingException e) {
72 e.printStackTrace();
73 } catch (FileNotFoundException e) {
74 e.printStackTrace();
75 }
76 }else{
77 throw new Exception("config目录下的配置文件SendMail. 78 }
79 log.debug(" 80 return fileContent;
81 }
82
83 /**
84 * <p>Title: parse 85 * <p>Description:发送邮件给指定的收件人和抄送人,同时进行一些简单的校验判断,如必填项的字段、type的值</p>
86 * @param 87 * @param type 邮件类型
88 */
89 private void parse 90 type=type.toLowerCase();//忽略type字段的大小写
91 try {
92 // 解析
93 Document doc = DocumentHelper.parseText( 94
95 // 判断type的值是否正确,type的值应是报文二级节点中的一个
96 String flag = doc.getRootElement().element(type) + "";
97 if (null == flag || flag.equals("null"))
98 throw new DocumentException(
99 "传入的type值不对,type的值应是SendMail.100
101 // 设置主机名称
102 Element hostEle = (Element) doc.selectSingleNode("/mail/" + type
103 + "/host");
104 if (null == hostEle || "".equals(hostEle.getTextTrim())) {
105 throw new DocumentException("邮件服务器域名或IP不能为空,请检查配置文件SendMail.106 }
107 mailInfo.setHost(hostEle == null ? "" : hostEle.getTextTrim());
108
109 // 设置发件人
110 Element fromEle = (Element) doc.selectSingleNode("/mail/" + type
111 + "/from");
112 if (null == fromEle || "".equals(fromEle.getTextTrim())) {
113 throw new DocumentException("发件人地址不能为空,请检查配置文件SendMail.114 }
115 mailInfo.setFrom(fromEle == null ? "" : fromEle.getTextTrim());
116
117 // 设置邮件主题
118 Element titleEle = (Element) doc.selectSingleNode("/mail/" + type
119 + "/title");
120 mailInfo.setTitle(titleEle == null ? "" : titleEle.getTextTrim());
121
122 // 设置收件人,对多个收件人的处理放在后面
123 Element toEle = (Element) doc.selectSingleNode("/mail/" + type
124 + "/to");
125 if (null == toEle || "".equals(toEle.getTextTrim())) {
126 throw new DocumentException("收件人地址不能为空,请检查配置文件SendMail.127 }
128 mailInfo.setTo(toEle == null ? "" : toEle.getTextTrim());
129
130 // 设置抄送,对多个抄送人的处理放在后面
131 Element ccEle = (Element) doc.selectSingleNode("/mail/" + type
132 + "/cc");
133 mailInfo.setCc(ccEle == null ? "" : ccEle.getTextTrim());
134
135 //设置发件人用户名
136 Element nameEle = (Element) doc.selectSingleNode("/mail/" + type
137 + "/username");
138 if(null==nameEle||"".equals(nameEle.getTextTrim())){
139 throw new DocumentException("发件人用户名不能为空,请检查配置文件SendMail.140 }
141 mailInfo.setUsername(nameEle == null ? "" : nameEle.getTextTrim());
142
143 //设置发件人密码
144 Element passEle = (Element) doc.selectSingleNode("/mail/" + type
145 + "/password");
146 if(null==passEle||"".equals(passEle.getTextTrim())){
147 throw new DocumentException("发件人密码不能为空,请检查配置文件SendMail.148 }
149 mailInfo.setPassword(passEle == null ? "" : passEle.getTextTrim());
150
151 } catch (DocumentException e) {
152 e.printStackTrace();
153 }
154 }
155
156 /**
157 * <p>Title: sendMailOfValidate</p>
158 * <p>Description:发送邮件的方法,Authenticator类验证</p>
159 */
160 private void sendMailOfValidate() {
161 Properties props = System.getProperties();
162 props.put("mail.smtp.host", mailInfo.getHost());//设置邮件服务器的域名或IP
163 props.put("mail.smtp.auth", "true");//授权邮件,mail.smtp.auth必须设置为true
164
165 String password=mailInfo.getPassword();//密码
166 try {
167 password=Encrypt.DoDecrypt(password);//如果密码经过加密用此方法对密码进行解密
168 } catch (NumberFormatException e1) {
169 //如果密码未经过加密,则对密码不做任何处理
170 }
171 //传入发件人的用户名和密码,构造MyAuthenticator对象
172 MyAuthenticator myauth = new MyAuthenticator(mailInfo.getUsername(),password);
173
174 //传入props、myauth对象,构造邮件授权的session对象
175 Session session = Session.getDefaultInstance(props, myauth);
176
177 //将Session对象作为MimeMessage构造方法的参数传入构造message对象
178 MimeMessage message = new MimeMessage(session);
179 try {
180 message.setFrom(new InternetAddress(mailInfo.getFrom()));//发件人
181
182 // 对多个收件人的情况进行处理,配置文件SendMail.
183 if (mailInfo.getTo() != null && !"".equals(mailInfo.getTo())) {
184 String to[] = mailInfo.getTo().split(",");
185 for (int i = 0; i < to.length; i++) {
186 message.addRecipient(Message.RecipientType.TO,
187 new InternetAddress(to[i]));// 收件人
188 }
189 }
190
191 // 对多个抄送人的情况进行处理,每个抄送人之间用逗号隔开的
192 if (mailInfo.getCc() != null && !"".equals(mailInfo.getCc())) {
193 String cc[] = mailInfo.getCc().split(",");
194 for (int j = 0; j < cc.length; j++) {
195 message.addRecipient(Message.RecipientType.CC,
196 new InternetAddress(cc[j]));// 抄送
197 }
198 }
199 message.setSubject(mailInfo.getTitle());// 主题
200
201 message.setText(mailInfo.getContent());// 内容
202
203 Transport.send(message);// 调用发送邮件的方法
204
205 log.debug("邮件发送成功");
206 } catch (AddressException e) {
207 e.printStackTrace();
208 } catch (MessagingException e) {
209 e.printStackTrace();
210 }
211 }
212
213 /**
214 * <p>Title: sendMail</p>
215 * <p>Description:外部程序调用的入口</p>
216 * @param type 邮件的类型,目前有三种,即logmessage、checkmessage、ordermessage,type只能传这三个值中一个,传其他的任何值都不行
217 * @param content 邮件的内容
218 * @throws Exception
219 */
220 public void sendMail(String type,String content) throws Exception{
221 log.debug("入参type="+type);
222 log.debug("入参content="+content);
223 if (null == type || "".equals(type) || null == content
224 || "".equals(content)) {
225 throw new Exception("方法的入参type和content字段的值都不能为空或null");
226 }
227
228 String //获得
229
230 parse//解析
231
232 mailInfo.setContent(content);//设置发送的内容
233
234 sendMailOfValidate();//发送邮件
235
236 }
237
238 /**
239 * 为了方便直接用main方法测试
240 * @param args
241 * @throws Exception
242 */
243 public static void main(String args[]) throws Exception {
244
245 SendMail mail = new SendMail();
246
247 // type类型,根据此字段去配置文件SendMail.
248 String type = "logmessage";
249
250 // 邮件的内容,实际开发中这个内容是前台传到后台
251 String content = "你好,欢饮使用JavaMail包开发邮件功能";
252
253 // 在其他类中调用时只能看到sendMail方法,为了保护内部细节,其它的方法都声明为私有的
254 mail.sendMail(type, content);
255 //这个项目中没有日志文件,所以我打印一句话来告诉自己程序已经成功运行
256 System.out.println("****success****");
257
258 }
259 }

说明:代码中的校验可能不太严谨和全面,因为这个配置文件是由开发人员自己配置,并且对配置文件也有详细的介绍,所以代码中就省略去了许多的校验。

SendMail.邮件功能开发邮件功能开发SendMail.

 1 <??><!-- 此处编码格式必须用UTF-8格式,这样和程序中的解码是统一的,不会出现乱码 -->
2 <mail>
3 <logmessage><!--报文的二级节点,为了使传入的type值对大小写不限制,故此处必须用小写 -->
4 <host>smtp.qq.com</host><!-- 邮件服务器域名或IP,必填项 -->
5 <from>838045782@qq.com</from><!-- 发件人 ,必填项 -->
6 <to>838045782@qq.com,taipeng0820@163.com</to><!-- 收件人,多个收件人之间用英文状态下的逗号隔开,必填项 -->
7 <cc>838045782@qq.com</cc><!-- 抄送,多个抄送人之间用英文状态下的逗号隔开-->
8 <title>test JavaMail</title><!-- 邮件主题-->
9 <username>838045782@qq.com</username><!-- 发件人邮箱的用户名,即email的全地址,必填项 -->
10 <password>123456</password><!-- 发件人邮箱的密码,像QQ邮箱如果设置了独立密码应输入独立密码,必填项,为了安全起见填写密码之前最好用Encrypt类的DoEncrypt方法加密 -->
11 </logmessage>
12
13 <checkmessage>
14 <host></host>
15 <from></from>
16 <to></to>
17 <cc></cc>
18 <title></title>
19 <username></username>
20 <password></password>
21 </checkmessage>
22
23 <ordermessage>
24 <host></host>
25 <from></from>
26 <to></to>
27 <cc></cc>
28 <title></title>
29 <username></username>
30 <password></password>
31 </ordermessage>
32 </mail>

注意:密码是必填项,由于是介绍,我把自己的密码给删掉换成了123456,实际中需根据需要配置邮件服务器域名、发件人、收件人、抄送人、用户名和密码。

 

result

运行方式:执行运行SendMail.java类中的main方式就可以测试了,测试之前请按说明配置

首次运行你可能会遇到以下的错误,所以note.txt文件就用来提供遇到的错误以及对应的解决方案

note.txt

java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
 at javax.mail.Session.loadProvidersFromStream(Session.java:928)
 at javax.mail.Session.access$000(Session.java:174)
 at javax.mail.Session$1.load(Session.java:870)
 at javax.mail.Session.loadResource(Session.java:1084)
 at javax.mail.Session.loadProviders(Session.java:889)
 at javax.mail.Session.<init>(Session.java:210)
 at javax.mail.Session.getDefaultInstance(Session.java:299)
 at mail.SendMail.sendMail(SendMail.java:31)
 at mail.SendMail.main(SendMail.java:50)
Exception in thread "main"
解决方案:在myeclipse的安装目录下搜索javaee.jar,然后用压缩软件打开,删除javax下的mail文件夹

java.lang.NoClassDefFoundError: com/sun/activation/registries/LogSupport
 at javax.activation.MailcapCommandMap.<init>(MailcapCommandMap.java:140)
 at javax.activation.CommandMap.getDefaultCommandMap(CommandMap.java:61)
 at javax.activation.DataHandler.getCommandMap(DataHandler.java:153)
 at javax.activation.DataHandler.getDataContentHandler(DataHandler.java:611)
 at javax.activation.DataHandler.writeTo(DataHandler.java:315)
 at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:264)
 at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1299)
 at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2071)
 at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2039)
 at javax.mail.Transport.send(Transport.java:119)
 at mail.SendMail.sendMailNoValidate(SendMail.java:48)
 at mail.SendMail.main(SendMail.java:96)
Exception in thread "main"
解决方案:在myeclipse的安装目录下搜索javaee.jar,然后用压缩软件打开,删除javax文件夹下的activation文件夹


javax.mail.SendFailedException: Sending failed;
  nested exception is:
 javax.mail.MessagingException: 503 Error: need EHLO and AUTH first !

 at javax.mail.Transport.send0(Transport.java:219)
 at javax.mail.Transport.send(Transport.java:81)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMailNoValidate(SendMailServiceImpl.java:210)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMail(SendMailServiceImpl.java:243)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.main(SendMailServiceImpl.java:261)
解决方案:props.put("mail.smtp.auth", "true");
 
javax.mail.SendFailedException: Sending failed;
  nested exception is:
 javax.mail.AuthenticationFailedException
 at javax.mail.Transport.send0(Transport.java:219)
 at javax.mail.Transport.send(Transport.java:81)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMailNoValidate(SendMailServiceImpl.java:211)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMail(SendMailServiceImpl.java:244)
 at com.asiainfo.bboss.sendmail.SendMailServiceImpl.main(SendMailServiceImpl.java:262)
解决方案: MyAuthenticator myauth = new MyAuthenticator(mailInfo.getUsername(),password);
 

运行截图如下:

图1:myeclipse后台打印的结果 此项目下没有log4j.properties文件,故会有红色的信息,代码中的log也没有打印出来

邮件功能开发

 

图2:去我的QQ邮箱收信---收件箱列表

邮件功能开发

 

图3:去我的QQ邮箱收信---邮件内容

邮件功能开发

 

图4:去我的163邮箱收信---收件箱列表

确认已经收到邮件,因为163邮件显示的是本人的真实姓名,这里就不截图了。

 

图5:去我的163邮箱收信---邮件内容

确认已经收到邮件,因为163邮件显示的是本人的真实姓名,这里就不截图了。

 

以上只是对javamail插件一个小小的应用,此插件也可以做收信、转发、答复、上传附件等功能,

希望更多的朋友可以接触到javamail插件,权当做一次宣传了。

 

原标题:邮件功能开发

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录