java mail实现Email的发送,完整代码

来源:互联网 发布:drm破解软件 编辑:程序博客网 时间:2024/05/05 09:53

1、对应用程序配置邮件会话

javax.mail.Session保存邮件系统的配置属性和提供用户验证的信息,发送email首先要获取session对象。

(1)Session.getInstance(java.util.Properties)获取非共享的session对象

(2)Session.getDefaultInstance(java.utilProperties)获取共享的session对象

    两者都必须建立Properties prop=new Properties()对象;

注意:一般对单用户桌面应用程序使用共享Session对象。

用SMTP协议发送Email时通常要设置mail.smtp.host(mail.protocol.host协议特定邮件服务器名)属性。

prop.put("mail.smtp.host","smtp.mailServer.com");

Session mailSession=Session.getInstance(prop);

注意:在真正使用创建的过程中,往往会让我们验证密码,这是我们要写一个密码验证类。javax.mail.Authenticator是一个抽象类,我们要写MyAuthenticator的密码验证类,该类继承Authenticator实现:

 protected PasswordAuthentication getPasswordAuthentication(){  
      return new PasswordAuthentication(String userName, String password);  
  }

这时我们创建Session对象:

      Session mailSession=Session.getInstance(prop,new MyAuthenticator(userName,Password));

并且要设置使用验证:prop.put("mail.smtp.auth","true");

使用 STARTTLS安全连接:prop.put("mail.smtp.starttls.enable","true");

2、配置邮件会话之后,要编写消息

要编写消息就要生成javax.mail.Message子类的实例或对Internet邮件使用javax.mail.interet.MimeMessage类。

(1)建立MimeMessage对象

MimeMessage扩展抽象的Message类,构造MimeMessage对象:

MimeMessage message=new MimeMessage(mailSession);

(2)消息发送者、日期、主题 

message.setFrom(Address theSender);

message.setSentDate(java.util.Date theDate);

message.setSubject(String theSubject);

(3)设置消息的接受者与发送者(寻址接收)

     setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者类型,但是一般用后两个,这样可以避免意外的替换或者覆盖接受者名单。定义接受者类型:

Message.RecipientType.TO:消息接受者

Message.RecipientType.CC:消息抄送者

Message.RecipientType.BCC:匿名抄送接收者(其他接受者看不到这个接受者的姓名和地址)

(4)设置消息内容

JavaMail基于JavaBean Activation FrameWork(JAF),JAF可以构造文本消息也可以支持附件。

设置消息内容时,要提供消息的内容类型-----即方法签名:

MimeMessage.setContent(Object theContent,String type);

也可以不用显式的制定消息的内容类型:MimeMessage.setText(String theText);

注意:建立地址javax.mail.InternetAddress toAddress=new InternetAddress(String address);

3、发送Email,这里以文本消息为例

javax.mail.Transport类来发送消息。这时Transport对象与相应传输协议通信,这里是SMTP协议。

Transport transport = mailSession.getTransport("smtp");//定义发送协议
transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);//登录邮箱
transport.send(message, message.getRecipients(RecipientType.TO));//发送邮件

下面是一个完整的代码:--------->>SendMail.java

  

原创粉丝点击