初始化设置邮件属性类,又来接收各个需要的参数
public class emailData {
private String host;
private String username;
private String password;
private String from; //发件人
private String[] recipients = null; //收件人
private String[] carbonCopy = null; //抄送人
private String[] adenoidBcc = null; //密送人
private String subject; //主题
private String content; //内容
private String contentType = null; //邮件内容格式(文本或html)
private String[] fileName = null; //附件文件名(提供一个附件或多个)
private boolean validate = false; // 是否需要身份验证
public emailData() {
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
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;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getRecipients() {
return recipients;
}
public void setRecipients(String[] recipients) {
this.recipients = recipients;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String[] getFileName() {
return fileName;
}
public String[] getCarbonCopy() {
return carbonCopy;
}
public void setCarbonCopy(String[] carbonCopy) {
this.carbonCopy = carbonCopy;
}
public String[] getAdenoidBcc() {
return adenoidBcc;
}
public void setAdenoidBcc(String[] adenoidBcc) {
this.adenoidBcc = adenoidBcc;
}
public void setFileName(String[] fileName) {
this.fileName = fileName;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
}
实现类
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.excec.bean.emailData;
/**
*
* Filename: Email.java
* Description:
* Copyright: Copyright (c) 2012-2013 All Rights Reserved.
* Company: golden-soft.com Inc.
* @author: Administrator
* @version: 1.0
* Create at: Apr 17, 2013 11:30:10 AM
*
* Modification History:
* Date Author Version Description
* ------------------------------------------------------------------
* Apr 17, 2013 Administrator 1.0 1.0 Version
*
*/
public class Email {
/**
* 创建一个内部类判断是否验证身份
*/
class MyAuthenticator extends Authenticator {
String userName = null;
String password = null;
public MyAuthenticator() {
super();
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
//发送邮件
public boolean sendMail(emailData email) {
String username = email.getUsername();
String password = email.getPassword();
String from = email.getFrom();
String[] recipients = email.getRecipients();
String subject = email.getSubject();
String content = email.getContent();
String contentType = email.getContentType();
String[] fileName = email.getFileName();
String[] carbonCopy = email.getCarbonCopy();
String[] adenoidBcc = email.getAdenoidBcc();
try {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties props = getProperties(email);
if (email.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(username, password);
}
//创建缺省的session对象
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
MimeMessage message = new MimeMessage(session); //邮件会话新建一个邮件信息
//检查邮件地址是否合法
if (from == null || from == "") {
throw new Exception("Error Email Address in From.");
}
//检查收件人
if (recipients == null || recipients.length <= 0) {
throw new Exception("Error Email Address in To.");
}
//设置源地址-发件人
InternetAddress addressFrom = new InternetAddress(from);
message.setFrom(addressFrom);
//设置目的地址-收件人
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
//设置抄送人地址
if (carbonCopy != null && carbonCopy.length > 0) {
InternetAddress[] addressCarbon = new InternetAddress[carbonCopy.length];
for (int i = 0; i < carbonCopy.length; i++) {
addressCarbon[i] = new InternetAddress(carbonCopy[i]);
}
message.setRecipients(Message.RecipientType.CC, addressCarbon); // 抄送人
}
//设置密送人地址
if (adenoidBcc != null && adenoidBcc.length > 0) {
InternetAddress[] addressAdenoid = new InternetAddress[adenoidBcc.length];
for (int i = 0; i < carbonCopy.length; i++) {
addressAdenoid[i] = new InternetAddress(adenoidBcc[i]);
}
message.setRecipients(Message.RecipientType.BCC, addressAdenoid); // 密送人
}
//设置邮件标题,中文编码-消息的主题
subject = MimeUtility.encodeText(new String(subject.getBytes(), "GB2312"), "GB2312","B");
message.setSubject(subject);
/*******************消息内容***********************************************/
//设置邮件内容,区分文本格式和HTML格式
if (contentType == null || contentType.equals("text")) {
message.setText(content);
} else if (contentType.equals("html")) {
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
//给消息对象设置内容
BodyPart mbp = new MimeBodyPart(); //新建一个存放信件内容的MimeBodyPart对象
mbp.setContent(content, "text/html;charset=gb2312");//给MimeBodyPart对象设置内容和格式/编码方式
//设置邮件附件
BodyPart mmp;
FileDataSource fileDataSource;
for (int i = 0; i < fileName.length; i++) {
mmp = new MimeBodyPart();
fileDataSource = new FileDataSource(fileName[i]);
mmp.setDataHandler(new DataHandler(fileDataSource));
/***************需要对附件文件名称进行转码,不然会出现乱码 ******************/
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
mmp.setFileName("=?GB2312?B?" + enc.encode(fileDataSource.getName().getBytes()) + "?=");
multipart.addBodyPart(mmp);
}
multipart.addBodyPart(mbp);
message.setContent(multipart);//把mm作为消息对象的内容
}
message.setSentDate(new Date()); //设置发送的时间
//保存邮件
message.saveChanges();
Transport transport = session.getTransport("smtp"); //设置邮件传输
transport.connect((String) props.get("mail.smtp.host"), username, password); //连接主机
transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO)); //发送邮件
System.out.println("Send Success !");
transport.close(); //关闭传输
return true;
} catch (AuthenticationFailedException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获得邮件会话属性
*/
public Properties getProperties(emailData email) {
Properties props = new Properties();//存储连接参数
props.put("mail.smtp.host", email.getHost());//邮件服务器"smtp.ym.163.com"
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "10000");
props.put("mail.smtp.timeout", "10000");
props.put("mail.smtp.auth", email.isValidate() ? "true" : "false");
return props;
}
//主方法
public static void main(String[] args) {
emailData email = new emailData();
email.setHost("smtp.163.com");//邮件服务器
email.setUsername("xxxx@163.com");//邮箱
email.setPassword("8888");//密码
email.setFrom("xxxx@163.com");//发送人自己
String list[] = { "xxx@163.com","xxx@163.com" };
email.setRecipients(list);//接收人
email.setSubject("AAAA");//标题
email.setContent("你好");//内容
email.setContentType("html");//类型
String fileName[] = {};//附件
email.setFileName(fileName);
String bcc[] = {};
email.setAdenoidBcc(bcc);//密送
String cc[] = {};
email.setCarbonCopy(cc);//抄送
email.setValidate(true);//设置验证
new Email().sendMail(email);
}
}