java mail实现Email的发送,完整代码
1、对应用程序配置邮件会话
首先, 导入jar
com.sun.mail
javax.mail
1.5.2
javax.mail.Session保存邮件系统的配置属性和提供用户验证的信息,发送email首先要获取session对象。
Session.getInstance(java.util.Properties)获取非共享的session对象
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实现:
protectedPasswordAuthentication getPasswordAuthentication(){return newPasswordAuthentication(String userName, String password);
}
这时我们创建Session对象:
Session mailSession=Session.getInstance(prop,newMyAuthenticator(userName,Password));
prop.put("mail.smtp.auth","true"); //并且要设置使用验证:
prop.put("mail.smtp.starttls.enable","true"); //使用 STARTTLS安全连接:
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
packagecom.tools;importjava.util.Calendar;importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.Message.RecipientType;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;public classSendMail {
@SuppressWarnings("static-access")public static voidsendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType)throwsMessagingException {//第一步:配置javax.mail.Session对象
System.out.println("为" + smtpHost + "配置mail session对象");
Properties props= newProperties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable", "true");//使用 STARTTLS安全连接//props.put("mail.smtp.port", "25");//google使用465或587端口
props.put("mail.smtp.auth", "true"); //使用验证//props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, newMyAuthenticator(
from, fromUserPassword));//第二步:编写消息
System.out.println("编写消息from——to:" + from + "——" +to);
InternetAddress fromAddress= newInternetAddress(from);
InternetAddress toAddress= newInternetAddress(to);
MimeMessage message= newMimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);//第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message yes");
}public static voidmain(String[] args) {try{
SendMail.sendMessage("smtp.gmail.com", "karemjohn@gmail.com","************", "karemjohn@gmail.com", "nihao","---------------wrwe-----------","text/html;charset=gb2312");
}catch(MessagingException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}class MyAuthenticator extendsAuthenticator {
String userName= "";
String password= "";publicMyAuthenticator() {
}publicMyAuthenticator(String userName, String password) {this.userName =userName;this.password =password;
}protectedPasswordAuthentication getPasswordAuthentication() {return newPasswordAuthentication(userName, password);
}
}
前边发过一个比较简单,这个就比较适用了,也方便以后使用:
第一个文件:------>>MailSenderInfo.java
功能:封装了发送邮件的基本信息
packagecom.util.mail;/*** 发送邮件需要使用的基本信息*/
importjava.util.Properties;public classMailSenderInfo {//发送邮件的服务器的IP和端口
privateString mailServerHost;private String mailServerPort = "25";//邮件发送者的地址
privateString fromAddress;//邮件接收者的地址
privateString toAddress;//登陆邮件发送服务器的用户名和密码
privateString userName;privateString password;//是否需要身份验证
private boolean validate = false;//邮件主题
privateString subject;//邮件的文本内容
privateString content;//邮件附件的文件名
privateString[] attachFileNames;/*** 获得邮件会话属性*/
publicProperties getProperties(){
Properties p= newProperties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");returnp;
}publicString getMailServerHost() {returnmailServerHost;
}public voidsetMailServerHost(String mailServerHost) {this.mailServerHost =mailServerHost;
}publicString getMailServerPort() {returnmailServerPort;
}public voidsetMailServerPort(String mailServerPort) {this.mailServerPort =mailServerPort;
}public booleanisValidate() {returnvalidate;
}public void setValidate(booleanvalidate) {this.validate =validate;
}publicString[] getAttachFileNames() {returnattachFileNames;
}public voidsetAttachFileNames(String[] fileNames) {this.attachFileNames =fileNames;
}publicString getFromAddress() {returnfromAddress;
}public voidsetFromAddress(String fromAddress) {this.fromAddress =fromAddress;
}publicString getPassword() {returnpassword;
}public voidsetPassword(String password) {this.password =password;
}publicString getToAddress() {returntoAddress;
}public voidsetToAddress(String toAddress) {this.toAddress =toAddress;
}publicString getUserName() {returnuserName;
}public voidsetUserName(String userName) {this.userName =userName;
}publicString getSubject() {returnsubject;
}public voidsetSubject(String subject) {this.subject =subject;
}publicString getContent() {returncontent;
}public voidsetContent(String textContent) {this.content =textContent;
}
}
第二个文件:----------->>SimpleMailSender.java
功能:一个只发送文本的发送器
packagecom.util.mail;importjava.util.Date;importjava.util.Properties;importjavax.mail.Address;importjavax.mail.BodyPart;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.Multipart;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;/*** 简单邮件(不带附件的邮件)发送器*/
public classSimpleMailSender {/*** 以文本格式发送邮件
*@parammailInfo 待发送的邮件的信息*/
public booleansendTextMail(MailSenderInfo mailInfo) {//判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro=mailInfo.getProperties();if(mailInfo.isValidate()) {//如果需要身份认证,则创建一个密码验证器
authenticator = newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}//根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession =Session.getDefaultInstance(pro,authenticator);try{//根据session创建一个邮件消息
Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址
Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者
mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中
Address to = newInternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);//设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息发送的时间
mailMessage.setSentDate(newDate());//设置邮件消息的主要内容
String mailContent =mailInfo.getContent();
mailMessage.setText(mailContent);//发送邮件
Transport.send(mailMessage);return true;
}catch(MessagingException ex) {
ex.printStackTrace();
}return false;
}/*** 以HTML格式发送邮件
*@parammailInfo 待发送的邮件信息*/
public static booleansendHtmlMail(MailSenderInfo mailInfo){//判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro=mailInfo.getProperties();//如果需要身份认证,则创建一个密码验证器
if(mailInfo.isValidate()) {
authenticator= newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}//根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession =Session.getDefaultInstance(pro,authenticator);try{//根据session创建一个邮件消息
Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址
Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者
mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中
Address to = newInternetAddress(mailInfo.getToAddress());//Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO,to);//设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息发送的时间
mailMessage.setSentDate(newDate());//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = newMimeMultipart();//创建一个包含HTML内容的MimeBodyPart
BodyPart html = newMimeBodyPart();//设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);//将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);//发送邮件
Transport.send(mailMessage);return true;
}catch(MessagingException ex) {
ex.printStackTrace();
}return false;
}
}
第三个文件:——————>>MyAuthenticator.java
功能:密码验证器
packagecom.util.mail;import javax.mail.*;/**密码验证器*/
public class MyAuthenticator extendsAuthenticator{
String userName=null;
String password=null;publicMyAuthenticator(){
}publicMyAuthenticator(String username, String password) {this.userName =username;this.password =password;
}protectedPasswordAuthentication getPasswordAuthentication(){return newPasswordAuthentication(userName, password);
}
}
程序入口,主函数:
public static voidmain(String[] args){//这个类主要是设置邮件
MailSenderInfo mailInfo = newMailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("chaofeng19861126@163.com");
mailInfo.setPassword("********");//您的邮箱密码
mailInfo.setFromAddress("chaofeng19861126@163.com");
mailInfo.setToAddress("karemjohn@gmail.com");
mailInfo.setSubject("设置邮箱标题");
mailInfo.setContent("设置邮箱内容");//这个类主要来发送邮件
SimpleMailSender sms = newSimpleMailSender();
sms.sendTextMail(mailInfo);//发送文体格式
sms.sendHtmlMail(mailInfo);//发送html格式
}
出自: http://blog.csdn.net/karem/article/details/4646071