1、验证发送邮件的邮箱
package com.easyoa.util;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Authenticator extends Authenticator {
String username = "你的邮箱";
String password = “邮箱密码”;
public Email_Authenticator() {
super();
}
public Email_Authenticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
2、发送邮件给对方,使用的是163的邮箱,所以host设置为“smtp.163.com”;
private String host = “smtp.163.com”;
private String mail_head_name = “邮件主题”;
private String mail_head_value = “邮件主题”;
private String mail_from = “发送邮件的邮箱”;
/**
* 邮件推送功能,
* @param mail_to ,对方邮箱,数组,可群发
* @param mail_subject,邮件标题
* @param mail_body, 邮件文字内容
* @param personalName,自己邮件中发件箱中的标题
* @param file,邮件附件数组,附件路径
* @return
*/
@Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
public boolean sendTransferMessage(String[] mail_to,String mail_subject,String mail_body,String personalName,String[] file)
throws Exception{
boolean flag = true;
try {
Properties props = new Properties();//获取系统环境
Authenticator auth = new Email_Authenticator();//进行邮件服务用户认证
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
System.out.println(props);
Session session = Session.getDefaultInstance(props,auth);
//设置session,和邮件服务器进行通讯
MimeMessage message = new MimeMessage(session);
message.setSubject(mail_subject);//设置邮件主题
message.setHeader(mail_head_name, mail_head_value);//设置邮件标题
message.setSentDate(new Date());//设置邮件发送时期
//邮件内容
MimeMultipart multipart = new MimeMultipart();
BodyPart msgBodyPart = new MimeBodyPart();//用来放置文本内容
msgBodyPart.setContent(mail_body,
"text/html;charset=UTF-8");
multipart.addBodyPart(msgBodyPart);
//添加附件,多附件
BodyPart attBodyPart ;
DataSource ds ;
if(file!=null&&file.length>0){
for (int i=0;i<file.length;i++){
attBodyPart = new MimeBodyPart();//用来放置附件
ds = new FileDataSource(new File(file[i]));
attBodyPart.setDataHandler(new DataHandler(ds));//设置DataHandler
attBodyPart.setFileName(ds.getName());//附件的显示名字
multipart.addBodyPart(attBodyPart);
}
}
//将邮件内容和附件加入到信息中
message.setContent(multipart);
Address address = new InternetAddress(mail_from,personalName);
message.setFrom(address);//设置邮件发送者的地址
//
Address toaddress = new InternetAddress(mail_to);//设置邮件接收者的地址
//
message.addRecipient(Message.RecipientType.TO,toaddress);
if(mail_to!=null&&mail_to.length>0){
Address[] toaddress = new InternetAddress[mail_to.length];
for(int i=0;i<mail_to.length;i++){
toaddress[i]=new InternetAddress(mail_to[i]);
}
message.addRecipients(Message.RecipientType.TO, toaddress);
System.out.println(message);
Transport.send(message);
}
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return flag;
}