java 发送mail,很久之前整过,没做记录,这次整理下做个记录。
java 发送mail
import java.awt.List;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.biokee.dlafis.util.GetProperties;
// http://www.cnblogs.com/snoopy/articles/129932.html
// http://blog.youkuaiyun.com/zlz3907/article/details/3958081
// http://www.4ucode.com/Study/Topic/445710
public class JavaMail {
String host;
String userName; // 邮箱用户名
String password ; // 密码
String from; // 发送的邮箱名称
String contentType; // 邮件内容格式(文本或html)
String replyTo; // 回复地址,默认是发送地址
String to; // 发给谁
String cc; // 抄送
String bcc; // 暗送
String subject; // 邮件议题
String body; // 内容
String fileName; // 附件路径(注意绝对路径和相对路径的选择)
// 用于保存发送附件的文件名列表
List arrFileName = new List();
// 用于收集附件名
public void attachFile(String fileName) {
this.arrFileName.add(fileName);
}
// 开始发送
@SuppressWarnings("static-access")
public boolean sendMail(String to,String cc ,String bcc, String subject, String body)
throws IOException {
// 处理中文乱码
subject = new String(subject.getBytes(),"gb2312");
body = new String(body.getBytes(),"gb2312");
// 创建Properties对象
Properties props = System.getProperties();
// 创建信件服务器
props.put("mail.smtp.host", this.host);
// props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true"); // 通过验证
props.put("mail.smtp.connectiontimeout", "10000"); //
props.put("mail.smtp.timeout", "10000"); //
// 得到默认的对话对象
Session session = Session.getDefaultInstance(props, null);
try {
// 创建一个消息,并初始化该消息的各项元素
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(this.from));
if (to.trim().length() > 0 || cc.trim().length()>0 || bcc.trim().length()>0) {
if(to!=null && to.trim().length() > 0 ){
sendAddress(to, msg,Message.RecipientType.TO);
}
if(cc!=null && cc.trim().length()>0){
sendAddress(cc, msg,Message.RecipientType.CC);
}
if(bcc!=null && bcc.trim().length()>0){
sendAddress(bcc, msg,Message.RecipientType.BCC);
}
} else {
System.out.println("None receiver! The program will be exit!");
System.exit(0);
}
// 添加议题
msg.setSubject(subject);
// 后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart();
// 获取附件
int FileCount = this.arrFileName.getItemCount();
if (FileCount > 0) {
for (int i = 0; i < FileCount; i++) {
MimeBodyPart mbp = new MimeBodyPart();
// 选择出附件名
fileName = arrFileName.getItem(i).toString();
// 得到数据源
FileDataSource fds = new FileDataSource(new String(fileName.getBytes(),"UTF-8"));
// 得到附件本身并至入BodyPart
mbp.setDataHandler(new DataHandler(fds));
// 得到文件名同样至入BodyPart
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(body);
mbp.setContent(body,"text/html;charset=gb2312");
mp.addBodyPart(mbp);
// 移走集合中的所有元素
arrFileName.removeAll();
// Multipart加入到信件
msg.setContent(mp);
} else {
// 设置邮件正文
if (contentType == null || contentType.equals("text")) {
msg.setText(body);
} else if (contentType.equals("html")) { // 未处理图片
System.out.println(11);
MimeBodyPart mbp = new MimeBodyPart();
// mbp.setText(body);
mbp.setContent(body,"text/html;charset=gb2312");
mp.addBodyPart(mbp);
// Multipart加入到信件
msg.setContent(mp);
}
}
// 设置回复的地址
InternetAddress[] add = new InternetAddress[1];
add[0] = new InternetAddress("xxxx@126.com");
msg.setReplyTo(add);
// 设置信件头的发送日期
msg.setSentDate(new Date());
msg.saveChanges();
// 发送信件
Transport transport = session.getTransport("smtp");
transport.connect(this.host, this.userName, this.password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
// msg.writeTo(System.out);
System.out.println("send mail ok");
} catch (MessagingException mex) {
System.out.println("send mail error"+mex.getMessage());
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
return false;
}
return true;
}
// 处理发送地址, to /cc /bcc 未校验邮件格式
private void sendAddress(String sendAddress, MimeMessage msg,RecipientType type)throws AddressException, MessagingException {
String[] arr = sendAddress.split(",");
// int ReceiverCount=1;
int receiverCount = arr.length;
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress(arr[i]);
}
msg.addRecipients(type, address);
}
}
/**
* 读取配置文件,并设置对应参数
*/
public void setSendMailParam(){
GetProperties g = new GetProperties();
this.host=g.getPropertiesValue("host").trim();
this.userName=g.getPropertiesValue("userName").trim();
this.password=g.getPropertiesValue("password").trim();
this.from=g.getPropertiesValue("from").trim();
this.replyTo=g.getPropertiesValue("replyTo").trim();
this.contentType=g.getPropertiesValue("contentType").trim();
}
/**
* @param args
*/
public static void main(String[] args) {
String content="测试来了 Hello world!<br/> " +
"<tabl border=\"1\" align=\"center\" cellpadding=\"1\" cellspacing=\"1\">" +
"<tr><td>name</td><td>address</td></tr>" +
"<tr><td>aaa</td><td>d:\\1.txt</td></tr></table>";//邮件内容
String subject="测试2";//邮件主题
String mailTo1="xxxx@163.com"; //接收邮件的地址1
String mailTo2="";
// String mailTo2="xxxx@126.com"; //接收邮件的地址2
String attach1="d:\\1.txt"; //附件一地址
String attach2="d:\\a.txt"; //附件二地址
JavaMail mail=new JavaMail();
mail.setSendMailParam();
try {
// mail.attachFile(attach1);
// mail.attachFile(attach2);
mail.sendMail(mailTo1+","+mailTo2, null,null, subject,content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
apache Commons-Email
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
import com.biokee.dlafis.util.GetProperties;
public class CommonsEmail {
String host;
String userName; // 邮箱用户名
String password ; // 密码
String from; // 发送的邮箱名称
String contentType; // 邮件内容格式(文本或html)
String replyTo; // 回复地址,默认是发送地址
String to; // 发给谁
String cc; // 抄送
String bcc; // 暗送
String subject; // 邮件议题
String body; // 内容
public static void main(String[] args) {
CommonsEmail emails = new CommonsEmail();
try {
emails.setSendMailParam();
emails.send("xxx@163.com",null,null);
// emails.sendAttachMail();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// http://wisekingokok.iteye.com/blog/456655
// http://www.blogjava.net/bulktree/archive/2008/04/07/191170.html
// http://apps.hi.baidu.com/share/detail/23398910
public void send(String to,String cc,String bcc) throws EmailException {
// SimpleEmail email = new SimpleEmail();
HtmlEmail email = new HtmlEmail();
//设置发送主机的服务器地址
email.setHostName(host);
//设置收件人邮箱 ,群发需要多次添加
email.addTo(to);
//发件人邮箱
email.setFrom(from);
//如果要求身份验证,设置用户名、密码,分别为发件人在邮件服务器上注册的用户名和密码
email.setAuthentication(userName, password);
//设置邮件的主题
email.setSubject("Hello, This is My First Email Application");
//邮件正文消息
// email.setMsg("I am bulktree This is JavaMail Application");
email.setHtmlMsg("I am bulktree This is JavaMail Application");
email.send();
System.out.println("The SimpleEmail send sucessful!!!");
}
public void sendAttachMail() throws EmailException{
// 创建一个Email附件 ,多附件多个处理
EmailAttachment emailattachment = new EmailAttachment();
emailattachment.setPath("d:/1.txt");
// emailattachment.setURL(new URL("http://www.blogjava.net/bulktree/picture/bulktree.jpg"));
emailattachment.setDisposition(EmailAttachment.ATTACHMENT);
emailattachment.setDescription("This is Smile picture");
emailattachment.setName("1.txt");
// 创建一个email
MultiPartEmail multipartemail = new MultiPartEmail();
multipartemail.setHostName(host);
multipartemail.addTo("xxxx@163.com", "josn");
multipartemail.setFrom(from, "feng");
multipartemail.setAuthentication(userName, password);
multipartemail.setSubject("This is a attachment Email");
multipartemail.setMsg("this a attachment Eamil Test");
//添加附件
multipartemail.attach(emailattachment);
//发送邮件
multipartemail.send();
System.out.println("The attachmentEmail send sucessful!!!");
}
/**
* 读取配置文件,并设置对应参数
*/
public void setSendMailParam(){
GetProperties g = new GetProperties();
this.host=g.getPropertiesValue("host").trim();
this.userName=g.getPropertiesValue("userName").trim();
this.password=g.getPropertiesValue("password").trim();
this.from=g.getPropertiesValue("from").trim();
this.replyTo=g.getPropertiesValue("replyTo").trim();
this.contentType=g.getPropertiesValue("contentType").trim();
}
}
GetProperties:
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class GetProperties {
private final Log log = LogFactory.getLog(getClass());
/**
* 获取Properties 某个键 -值
* @param name
* @return
*/
public String getPropertiesValue(String name){
String propertiesFile="application.properties";
URL url=getClass().getResource("/" + propertiesFile);
String value=null;
try {
InputStream in = url.openStream();
Properties p = new Properties();
p.load(in);
in.close();
value = p.getProperty(name);
} catch (Exception e) {
log.error(e);
e.printStackTrace();
}
return value;
}
}
spring 发送mail 就不写了,给个参考链接
http://huqilong.blog.51cto.com/53638/133210
附件是需要的jar 包!