`
mathzxw2002
  • 浏览: 19156 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JavaMail的使用

阅读更多
Apusic上用JavaMail发邮件
0. JavaMail基本介绍
JavaMail是属于J2EE框架中的一部分,主要是为简化Mail部分开发工作。使用JavaMail发送邮件需要以下步骤:
1)初始化Session实例;
在初始化Session实例中有两种方式:使用JNDI初始化和在代码中自行完成初始化。
★ 如果SMTP不需要认证,则不再做其他工作;
★ 如果SMTP需要认证,则确定在Session中提供嵌入认证信息,还是由3)Transport完成认证过程。
2)初始化Message实例,填充相关信息;
3)初始化Transport实例,连接到远程SMTP服务器,发送邮件。
在初始化Transport实例时也有两种情况:
★ 如果SMTP不需要认证,可以直接调用send()函数发送邮件,应用服务器会在后台调用connect()函数完成谁,进行邮件发送;
★ 如果SMTP需要认证,需要调用connect()函数,并提供认证需要的用户名/密码,才可以正确发送邮件。

1. javax.mail.Session的初始化
1.1. 使用JNDI初始化(配置JavaMail的JNDI)
在Apusic的J2EE应用中找到apusic-application.xml文件,增加<mail-session>部分,示例如下:
<apusic-application>
<module uri="web.war">
  <web />
</module>
<mail-session>
  <jndi-name>javamail/myMail</jndi-name>
  <property name="mail.transport.protocol" value="smtp" />
  <property name="mail.smtp.host" value="smtp.163.com" />
  <property name="mail.smtp.user" value="user" />
  <property name="mail.smtp.password" value="password" />
  <property name="mail.smtp.auth" value="true" />
  <property name="mail.from" value="user@163.com" />
</mail-session>
</apusic-application>

1.1.1. 通过JNDI找到JavaMail
1.1.1.1. 使用远程访问获得JavaMail
Hashtable env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.apusic.naming.jndi.CNContextFactory");
env.put(Context.PROVIDER_URL,"iiop://localhost:6888");
//插入相关验证信息
env.put(Context.SECURITY_CREDENTIALS,"admin" ) ;
env.put(Context.SECURITY_PRINCIPAL,"admin");
Context initCtx=new InitialContext(env);
System.out.println(initCtx.PROVIDER_URL);
//通过RMI 取得
Session myMailSession = (Session) initCtx.lookup("javamail/myMailNoAuth");
1.1.1.2. 使用Apusic默认方式获得JavaMail
Context initCtx = new InitialContext();
Session myMailSession = (Session) initCtx.lookup("javamail/myMailNoAuth");
System.out.println(myMailSession.getProperty("mail.smtp.host"));

1.1.2. 通过资源注入配置JavaMail
@Resource(mappedName = "javamail/myMailAuth", type = javax.mail.Session.class, shareable = true, authenticationType = Resource.AuthenticationType.CONTAINER, description = "my email with auth")
private Session myAuthMailSession;
或者
@Resource(mappedName = "javamail/myMailAuth")
private Session myAuthMailSession;

1.2. 在代码中初始化
1.2.1. 无须认证的初始化
final Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.host", "localhost");
Session myMailSession = Session.getInstance(props);
1.2.2. 需要认证的初始化(Session实例构造时提供认证支持)
final Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.163.com");
Session myMailSession = Session.getInstance(props, new Authenticator() {
  public PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication("user", "password");} });
1.2.3. 需要认证的初始化(Session配置参数提供认证支持)
myMailSession.setPasswordAuthentication(
  new URLName(props.getProperty("mail.transport.protocol")+"://"+  
                 props.getProperty("mail.smtp.user")+"@"+  
                 props.getProperty("mail.smtp.host")),  
        new PasswordAuthentication(props.getProperty("mail.smtp.user"),  
                 props.getProperty("mail.smtp.password")));  

1.2.4. 需要认证的初始化(Transport配置参数提供认证支持)
  // 发送邮件
  javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
  myTransport.connect("smtp.163.com", "user", "password");
  myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
  myTransport.close();
  
1.4. 对Session调试的配置
● 可以在mail-session中加入<property name="mail.debug" value="true" />
● 可以在Session初始化前加入props.put("mail.debug", "true");
● 可以在Session初始化后,通过代码控制myMailSession.setDebug(true);

1.5. Properties的解释
◆ mail.store.protocol:用于检索邮件的协议
◆ mail.transport.protocol:用于传送邮件的协议
◆ mail.host:默认的主机名,默认是本地计算机。
◆ mail.user:默认的用户名。
◆ mail.from:默认的返回地址。
◆ mail.debug:是否输出DEBUG信息。默认为False。
◆ mail.protocol.host:指定协议的主机名,没有指定就用mail.host。例如:mail.smtp.host=smtp.163.com
◆ mail.protocol.user:指定协议的用户名,没有指定就用mail.user。例如:mail.smtp.user=user
◆ mail.protocol.from:指定协议的返回地址,没有指定就用mail.from。例如:mail.smtp.from=user@163.com
◆ mail.smtp.auth:如果是True,就会登录SMTP服务器,获得授权才能发送邮件。默认为False。


2. 通过JavaMail发送邮件
2.1. 通过无须认证的SMTP发邮件
  final Properties props = new Properties();
  props.put("mail.transport.protocol", "smtp");
  props.put("mail.smtp.auth", "false");
  props.put("mail.smtp.host", "localhost");
  try {
   Session myMailSession = Session.getInstance(props);
   myMailSession.setDebug(true); // 打开DEBUG模式
   Message msg = new MimeMessage(myMailSession);
   msg.setFrom(new InternetAddress("user@163.com"));
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
   msg.setContent("I have a email test!", "text/plain");
   msg.setSentDate(new java.util.Date());
   msg.setSubject("Test");
   msg.setText("This is a test!\n");
   System.out.println("1.Please wait for sending one...");

   // 发送邮件
   // javax.mail.Transport.send(msg); // 与下面四行的功能一样
   javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
   myTransport.connect();
   myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
   myTransport.close();
  
   System.out.println("2.Your message had send!");
  } catch (Exception error) {
   System.out.println("*.I am sorry to tell you the fail for " + error);
  }

注:测试可以使用Microsft IIS SMTP 服务,安装好启动服务后,还需要进入“IIS管理器”,增加一个“远程域”,对于“远程域”的“出站安全性”需要把用户名和密码加上(就是平时发邮件时登录用的用户名/密码),否则邮件发不出去。

2.2. 通过需要认证的SMTP发邮件
2.2.1. 需要认证的初始化(Session实例构造时提供认证支持)
final Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.163.com");

try {
  Session myMailSession = Session.getInstance(props, new Authenticator() {
   public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("user", "password");
   }
  });
  myMailSession.setDebug(true); // 打开DEBUG模式
  InternetAddress address = new InternetAddress("user@163.com");
  String message = "I have a email test!";
  Message msg = new MimeMessage(myMailSession);
  msg.setFrom(address);
  msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
  msg.setContent(message, "text/plain");
  msg.setSentDate(new java.util.Date());
  msg.setSubject("Test");
  msg.setText("This is a test!\n");
  out.println("1.Please wait for sending...");
 
  // 发送邮件
  javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
  myTransport.connect();
  myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
  myTransport.close();
  // javax.mail.Transport.send(msg); // 注释上四行,打开这行代码,功能一样
  out.println("2.Your message had send!");
} catch (Exception error) {
  out.println("*.I am sorry to tell you the fail for " + error);
}

2.2.2. 需要认证的初始化(Session配置参数提供认证支持)
final Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.163.com");

try {
  Session myMailSession = Session.getInstance(props);
  myMailSession.setDebug(true); // 打开DEBUG模式
  myAuthMailSession.setPasswordAuthentication(
   new URLName("smtp://user@host", new PasswordAuthentication("user","password")); 
  InternetAddress address = new InternetAddress("user@163.com");
  String message = "I have a email test!";
  Message msg = new MimeMessage(myMailSession);
  msg.setFrom(address);
  msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
  msg.setContent(message, "text/plain");
  msg.setSentDate(new java.util.Date());
  msg.setSubject("Test");
  msg.setText("This is a test!\n");
  out.println("1.Please wait for sending...");
 
  // 发送邮件
  javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
  myTransport.connect();
  myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
  myTransport.close();
  // javax.mail.Transport.send(msg); // 注释上四行,打开这行代码,功能一样
  out.println("2.Your message had send!");
} catch (Exception error) {
  out.println("*.I am sorry to tell you the fail for " + error);
}

2.2.3. 需要认证的初始化(Transport配置参数提供认证支持)
  final Properties props = new Properties();
  props.put("mail.transport.protocol", "smtp");
  props.put("mail.smtp.auth", "true");

  try {
   Session myMailSession = Session.getInstance(props);
   myMailSession.setDebug(true); // 打开DEBUG模式
   Message msg = new MimeMessage(myMailSession);
   msg.setFrom(new InternetAddress("user@163.com"));
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zhuyuanxiang@apusic.com"));
   msg.setContent("I have a email test!", "text/plain");
   msg.setSentDate(new java.util.Date());
   msg.setSubject("Test");
   msg.setText("This is a test!\n");
   System.out.println("1.Please wait for sending two...");

   // 发送邮件
   javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
   myTransport.connect("smtp.163.com", "user", "password");
   myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
   myTransport.close();
   // javax.mail.Transport.send(msg); // 这行不能使用。
   System.out.println("2.Your message had send!");
  } catch (Exception error) {
   System.out.println("*.I am sorry to tell you the fail for " + error);
  }
}

注:资源注入的Session发送邮件时:
无须认证的SMTP,可以参考2.1.
需要认证的SMTP,可以参考2.2.1.

参考:
http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://commons.apache.org/email/userguide.html
http://www.blogjava.net/Unmi/archive/2007/06/07/124179.html
http://unmi.blogcn.com/diary,117630488.shtml


Apusic Stduio打包的示例工程。
http://zhuyuanxiang.iteye.com/topics/download/d6f5c3a9-9cd9-30be-9b64-9e311900b304
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics