本文包含四部分,一、直接发送一封现有的邮件文件 二、在Web应用中增加邮件发送功能 三、使用JavaMail进行邮件开发的一些技巧 四、编码过程中遇到的异常及解决
一、直接发送一封现有的邮件文件
要求:直接发送系列3中生成的demo3.eml.
代码如下:
package info.zoio.javamail; import java.io.FileInputStream; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; public class Demo4 { public static void main(String[] args) { Properties props = new Properties(); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.126.com"); //props.setProperty("mail.port", "25"); Session session = Session.getInstance(props, new Authenticator() { //策略模式 protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication("java_mail_test", "h123456"); } }); session.setDebug(true); try { /* Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]")); msg.setSubject("JavaMail API"); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected],[email protected]")); msg.setContent("<span style='color:red'>JavaMail开发测试</span>","text/html;charset=GBK"); Transport.send(msg);*/ Message msg = new MimeMessage(session, new FileInputStream("F:\\Java邮件\\demo3.eml")); Transport.send(msg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
二、在Web应用中增加邮件发送功能(源码见附件)
新建Web工程JavaMailWeb.
1.普通方式
直接使用SendMailServlet调用Demo4类的main方法.
说明:部署到tomcat时需要添加mail.jar和activation.jar
2.用tomcat支持的JNDI资源方式
步骤:
a.配置JNDI资源;
b.将mail.jar拷贝到<tomcat_home>/common/lib目录下(jdk1.6以下版本需要添加activation.jar)
c.在java程序中使用JNDI API获取mail的session对象
a.根据tomcat帮助文档,在WebRoot/META-INF文件夹下创建context.xml
添加如下内容
<Context>
<!-- JNDI -->
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"
mail.smtp.host="smtp.126.com"
mail.smtp.suth="true"
mail.transport.protocol="smtp"/>
</Context>
b.重写SendMailServlet.java
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
msg.setSubject("Tomcat JNDI Test");
msg.setText("The email which caotains JNDI test is sent by humyna");
Transport transport = session.getTransport();
transport.connect("smtp.126.com",25,"java_mail_test", "h123456");
transport.sendMessage(msg,InternetAddress.parse("[email protected]"));
transport.close();
c.将mail.jar和activation.jar拷贝到<tomcat_home>/common/lib目录下。(并删除掉WebRoot/WEB-INF/lib下的两个jar包)
三、使用JavaMail进行邮件开发的一些技巧
1.解决附件中中文显示的问题,使用工具类进行编码
attch1.setFileName(MimeUtility.encodeText("attach1哈哈.txt"));
2.如何在程序中设置默认回信地址
msg.setReplyTo(new Address[]{new InternetAddress("[email protected]")});
3.关于收件邮箱油耗显示收发件人的名称
msg.setFrom(new InternetAddress(" \" " + MimeUtility.encodeText("十井") + " \" <[email protected]>"));
4.JDK1.6以下需要添加activation.jar
四、编码过程中遇到的异常及解决
1.错误一
Exception in thread "main" javax.mail.internet.ParseException: Expected ';', got "/" at javax.mail.internet.ParameterList.<init>(ParameterList.java:289) at javax.mail.internet.ContentType.<init>(ContentType.java:114) at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1331) at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107) at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075) at info.zoio.javamail.Demo3.main(Demo3.java:77)
解决:MimeMultipart msgMultipart = new MimeMultipart("multipart/mixed");
改为:MimeMultipart msgMultipart = new MimeMultipart("mixed");
原因:可查看MimeMultipart的构造函数,说的是subtype
2.错误二(tomcat支持的JNDI资源方式)
java.lang.ClassCastException: javax.mail.Session at info.zoio.web.mail.servlets.SendMailServlet.doPost(SendMailServlet.java:54) at info.zoio.web.mail.servlets.SendMailServlet.doGet(SendMailServlet.java:33) at javax.servlet.http.HttpServlet.service(HttpServlet.java:627) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:843) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:679) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1293) at java.lang.Thread.run(Unknown Source)
原因:由于内容中加载了两份mail.jar和activation.jar
解决:需要将web工程lib下的相关包删除
3.错误三
com.sun.mail.smtp.SMTPSendFailedException: 553 authentication is required,smtp4,jdKowED5aUm4YExQXrqGAw--.795S2 1347182776 ; nested exception is: com.sun.mail.smtp.SMTPSenderFailedException: 553 authentication is required,smtp4,jdKowED5aUm4YExQXrqGAw--.795S2 1347182776 at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2114) at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1618) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119) at javax.mail.Transport.send0(Transport.java:195) at javax.mail.Transport.send(Transport.java:124) at info.zoio.web.mail.servlets.SendMailServlet.doPost(SendMailServlet.java:64) at info.zoio.web.mail.servlets.SendMailServlet.doGet(SendMailServlet.java:33) at javax.servlet.http.HttpServlet.service(HttpServlet.java:627) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:843) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:679) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1293) at java.lang.Thread.run(Unknown Source) Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 553 authentication is required,smtp4,jdKowED5aUm4YExQXrqGAw--.795S2 1347182776 at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1625) ... 19 more
网上说的原因是:
1)发件服务器地址与邮件的发件人地址不同
2)发件时使用的登陆发件服务器的用户名和发件人不同,比如你填的发件人是[email protected],你却用其它的用户名比如aaachii登陆发件服务器,无论你是否知道aaachii这个账号的密码都会返回上书的验证错误
3)最简单的情况:你把发件用的密码弄错了
我的解决方法是(按照上面的方法测试了没什么了帮助):
transport.send(msg,InternetAddress.parse("[email protected]"));改成
transport.sendMessage(msg,InternetAddress.parse("[email protected]"));
(JavaMail实践完)
下一步:实现安卓平台邮件收发功能(计划支持gmail\126\163)。