您的位置:首页 > 编程语言 > Java开发

java mail 发送邮件

2014-06-26 00:09 148 查看


广告:美图点评内部推荐入口。

mail.jar 下载链接:
http://download.csdn.net/detail/heisekankan/7552643
使用maven构建:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<groupId>TestSax</groupId>
<artifactId>TestSax</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>net.sf.staccatocommons</groupId>
<artifactId>commons-lang</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

</project>


首先定义一个邮件类:

import java.io.File;
import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: WEISHI
* Date: 14-6-25
* Time: 下午10:25
* To change this template use File | Settings | File Templates.
*/
public class Email {
private String context;//邮件正文
private String title;//邮件标题
private List<File> attenchment;//附件列表
private String addto;//to 的地址
private String from;// from地址

public Email(String context, String title, String from, String addto) {
this.context = context;
this.title = title;
this.from = from;
this.addto = addto;
}

public Email(String context, String title, List<File> attenchment, String addto, String from) {
this.context = context;
this.title = title;
this.attenchment = attenchment;
this.addto = addto;
this.from = from;
}

public String getContext() {
return context;
}

public void setContext(String context) {
this.context = context;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public List<File> getAttenchment() {
return attenchment;
}

public void setAttenchment(List<File> attenchment) {
this.attenchment = attenchment;
}

public String getAddto() {
return addto;
}

public void setAddto(String addto) {
this.addto = addto;
}

public String getFrom() {
return from;
}

public void setFrom(String from) {
this.from = from;
}

}
定义一个邮件服务器类:

/**
* Created with IntelliJ IDEA.
* User: WEISHI
* Date: 14-6-25
* Time: 下午10:17
* To change this template use File | Settings | File Templates.
*/
public class Server {
private String host;//邮件服务器主机名
private String port;//邮件服务器端口号
private String username;//用户名
private String password;//密码

public Server(String host, String port, String username, String password) {
this.host = host;
this.port = port;

this.username = username;
this.password = password;
}

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public String getPort() {
return port;
}

public void setPort(String port) {
this.port = port;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}


登录验证类:

/**
* Created with IntelliJ IDEA.
* User: WEISHI
* Date: 14-6-25
* Time: 下午7:35
* To change this template use File | Settings | File Templates.
*/
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class EmailAuhor extends  Authenticator {
private String username;
private String password;

public EmailAuhor(String username, String password) {
this.username = username;
this.password = password;
}
public EmailAuhor(){
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}

}


定义一个 发送类:

/**
* Created with IntelliJ IDEA.
* User: WEISHI
* Date: 14-6-25
* Time: 下午7:22
* To change this template use File | Settings | File Templates.
*/

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SendMail {
private static final Logger logger = LogManager.getLogger(SendMail.class);
public String send(Server server,Email email){

String result=null;
Session session=null;
Properties prop=System.getProperties();
prop.put("mail.smtp.host",server.getHost());
prop.put("mail.smtp.sendpartial","true");
prop.put("mail.smtp.port",server.getPort());
if(StringUtils.isBlank(server.getUsername())){//是否是匿名邮件服务器
session = Session.getDefaultInstance(prop, null);
}else {
prop.put("mail.smtp.auth","true");
EmailAuhor auhor=new EmailAuhor(server.getUsername(),server.getPassword());
session=Session.getInstance(prop,auhor);
}

try {
MimeMessage message=new MimeMessage(session);  //创建邮件
message.setFrom(new InternetAddress(email.getFrom()));  //设置发件人地址
InternetAddress[] toAddr=InternetAddress.parse(email.getAddto());
message.addRecipients(Message.RecipientType.TO, toAddr);
message.setSubject(email.getTitle());
Multipart multipart = new MimeMultipart();   //设置发送内容
MimeBodyPart contentPart= new MimeBodyPart();
contentPart.setText(email.getContext());
multipart.addBodyPart(contentPart);
//设置附件
if(email.getAttenchment()!=null && email.getAttenchment().size()>0){
for(int i=0;i<email.getAttenchment().size();i++){
MimeBodyPart attachmentPart=new MimeBodyPart();
FileDataSource source=new FileDataSource(email.getAttenchment().get(i));
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(MimeUtility.encodeWord(email.getAttenchment().get(i).getName(), "gb2312", null));
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
//登录服务器
if(StringUtils.isBlank(server.getUsername())){
Transport.send(message);
}else {
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(message,message.getAllRecipients());
transport.close();
}

logger.info("发送成功" + email.getFrom());
result="发送成功";
} catch (MessagingException mex) {

result="邮箱服务器发送错误!";
if(mex instanceof AuthenticationFailedException){
result="用户名或密码错误!";
}
mex.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
} catch (UnsupportedEncodingException e) {

result="系统发生异常";
e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
return result;

}
}
写一个测试类:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: WEISHI
* Date: 14-6-25
* Time: 下午9:07
* To change this template use File | Settings | File Templates.
*/
public class TestEmail {
public static void main(String[] args){
List list=new ArrayList();
list.add(new File("c:\\WEI_SHI_201312_BillingFcstReportExport.xls"));
Server server=new Server("smtp.163.com","25","邮件地址","密码");
Email email=new Email("测试邮件改版","测试邮件改版","邮件from地址","邮件to的地址,用逗号隔开就是to多人");
SendMail sendemail=new SendMail();
String result = sendemail.send(server,email);
System.out.println(result);

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息