Java Mail:Session、Message详解

  本文来自: 高爽|Coder,原文地址: http://blog.csdn.net/ghsau/article/details/17909093,转载请注明。
       上篇文章介绍了JavaMail并实现了一个发送邮件的简单示例,JavaMail API使用上非常灵活,比如,服务器信息可以设置到Session中,也可以设置到Transport中,收件人可以设置到Message中,也可以设置到Transport中,如何使用,取决于我们应用程序中的实际情况。本文详细的介绍一下这三个类的主要方法。

Session


       Session用于收集JavaMail运行过程中的环境信息,它可以创建一个单例的对象,也可以每次创建新的对象,Session没有构造器,只能通过如下方法创造实例:
static SessiongetDefaultInstance(Properties props)
          Get the default Session object.
static SessiongetDefaultInstance(Properties props,Authenticator authenticator)
          Get the default Session object.
static SessiongetInstance(Properties props)
          Get a new Session object.
static SessiongetInstance(Properties props,Authenticator authenticator)
          Get a new Session object.
       getDefaultInstance得到的始终是该方法初次创建的缺省的对象,而getInstance得到的始终是新的对象,Authenticator的使用后面会说到。通过Session可以创建Transport(用于发送邮件)和Store(用于接收邮件),Transport和Store是JavaMail API中定义好的接口,通过上文我们知道JavaMail分为API和service provider两部分,API定义了相关接口(eg.:Transport and Store),service provider中实现了这些接口,这些实现类配置在名为 javamail.providersjavamail.default.providers的文件中,该文件放在mail.jar/smtp.jar/pop3.jar/imap.jar中的META-INF下,文件内容格式如:
  1. # JavaMail IMAP provider Sun Microsystems, Inc  
  2. protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc;  
  3. protocol=imaps; type=store; class=com.sun.mail.imap.IMAPSSLStore; vendor=Sun Microsystems, Inc;  
  4. # JavaMail SMTP provider Sun Microsystems, Inc  
  5. protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc;  
  6. protocol=smtps; type=transport; class=com.sun.mail.smtp.SMTPSSLTransport; vendor=Sun Microsystems, Inc;  
  7. # JavaMail POP3 provider Sun Microsystems, Inc  
  8. protocol=pop3; type=store; class=com.sun.mail.pop3.POP3Store; vendor=Sun Microsystems, Inc;  
  9. protocol=pop3s; type=store; class=com.sun.mail.pop3.POP3SSLStore; vendor=Sun Microsystems, Inc;  
       每一行声明了协议名称、类型、实现类、供应商、版本等信息,如果需要自己实现相应的协议,必须按照该格式配置好,Java Mail API中才能正确的调用到。Session中提供的创建Trasnsport和Store的方法如下:
 StoregetStore()
          Get a Store object that implements this user's desired Store protocol.
 StoregetStore(Provider provider)
          Get an instance of the store specified by Provider.
 StoregetStore(String protocol)
          Get a Store object that implements the specified protocol.
 StoregetStore(URLName url)
          Get a Store object for the given URLName.
 TransportgetTransport()
          Get a Transport object that implements this user's desired Transport protcol.
 TransportgetTransport(Address address)
          Get a Transport object that can transport a Message of the specified address type.
 TransportgetTransport(Provider provider)
          Get an instance of the transport specified in the Provider.
 TransportgetTransport(String protocol)
          Get a Transport object that implements the specified protocol.
 TransportgetTransport(URLName url)
          Get a Transport object for the given URLName.
       可以看到,重构了很多,这些方法最终都会去解析上文提到的配置文件,找到对应配置信息。

Message


       Message是邮件的载体,用于封装邮件的所有信息,Message是一个抽象类,已知的实现类有MimeMessage。一封完整的邮件都有哪些信息呢?我们打开一个邮件客户端,我用的是FoxMail,新建一封邮件,如下图所示:
       这就是一封完整的邮件包含的所有信息,默认情况下是没有暗送和回复设置的,可以通过菜单栏-->查看-->暗送地址/回复地址来显示出来,回复地址默认情况下为发件人,暗送是比较猥琐的发邮件方式,暗送邮件除了被暗送者,没有人能知道暗送给谁了,邮件头信息中也不会记录。下面来看下Message中设置邮件信息的一些方法。

发件人

abstract  voidsetFrom()
          Set the "From" attribute in this Message.
abstract  voidsetFrom(Address address)
          Set the "From" attribute in this Message.
       现在大多数SMTP服务器要求发件人与连接账户必须一致,否则会抛出验证失败的异常,这样是防止用户伪装成其它人的账户恶意发送邮件。

收件人/抄送人/暗送人

voidsetRecipient(Message.RecipientType type,Address address)
          Set the recipient address.
abstract  voidsetRecipients(Message.RecipientType type,Address[] addresses)
          Set the recipient addresses.
       第一个方法设置单个人,第二个方法设置多个人。方法中第一个参数涉及到另一个类RecipientType,该类是Message的静态内部类,期内有三个常量值:
static Message.RecipientTypeBCC
          The "Bcc" (blind carbon copy) recipients.
static Message.RecipientTypeCC
          The "Cc" (carbon copy) recipients.
static Message.RecipientTypeTO
          The "To" (primary) recipients.
       TO - 收件人;CC - 抄送人;BCC - 暗送人。

回复人

 voidsetReplyTo(Address[] addresses)
          Set the addresses to which replies should be directed.
       设置收件人收到邮件后的回复地址。

标题

abstract  voidsetSubject(String subject)
          Set the subject of this message.
       设置邮件标题/主题。

内容

 voidsetContent(Multipart mp)
          This method sets the given Multipart object as this message's content.
 voidsetContent(Object obj,String type)
          A convenience method for setting this part's content.
 voidsetText(String text)
          A convenience method that sets the given String as this part's content with a MIME type of "text/plain".
       设置邮件文本内容、HTML内容、附件内容。

示例


       下面来看一个稍复杂点的示例:
  1. public class JavaMailTest2 {  
  2.   
  3.     public static void main(String[] args) throws MessagingException {  
  4.         Properties props = new Properties();  
  5.         // 开启debug调试  
  6.         props.setProperty("mail.debug""true");  
  7.         // 发送服务器需要身份验证  
  8.         props.setProperty("mail.smtp.auth""true");  
  9.         // 设置邮件服务器主机名  
  10.         props.setProperty("mail.host""smtp.163.com");  
  11.         // 发送邮件协议名称  
  12.         props.setProperty("mail.transport.protocol""smtp");  
  13.           
  14.         // 设置环境信息  
  15.         Session session = Session.getInstance(props, new Authenticator() {  
  16.             // 在session中设置账户信息,Transport发送邮件时会使用  
  17.             protected PasswordAuthentication getPasswordAuthentication() {  
  18.                 return new PasswordAuthentication("java_mail_001""javamail");  
  19.             }  
  20.         });  
  21.           
  22.         // 创建邮件对象  
  23.         Message msg = new MimeMessage(session);  
  24.         // 发件人  
  25.         msg.setFrom(new InternetAddress("java_mail_001@163.com"));  
  26.         // 多个收件人  
  27.         msg.setRecipients(RecipientType.TO, InternetAddress.parse("java_mail_002@163.com,java_mail_003@163.com"));  
  28.         // 抄送人  
  29.         msg.setRecipient(RecipientType.CC, new InternetAddress("java_mail_001@163.com"));  
  30.         // 暗送人  
  31.         msg.setRecipient(RecipientType.BCC, new InternetAddress("java_mail_004@163.com"));  
  32.           
  33.         // 主题  
  34.         msg.setSubject("中文主题");  
  35.         // HTML内容  
  36.         msg.setContent("<div align=\"center\">你好啊</div>""text/html;charset=utf-8");  
  37.           
  38.         // 连接邮件服务器、发送邮件、关闭连接,全干了  
  39.         Transport.send(msg);  
  40.     }  
  41.   
  42. }  
       本文来自: 高爽|Coder,原文地址: http://blog.csdn.net/ghsau/article/details/17909093,转载请注明。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值