本例采用163邮箱发送邮件,通过读取properties文件获取参数。在整个过程中遇到很了一个大坑。
邮件主题不能为test,测试等关键字,否则会被邮箱服务器视为非法邮件。
另注意:
在邮件登陆过程中需要使用验证方式,即将用户和密码封装在Authenticator对象里,貌似现在邮箱都必须进行登陆验证
package com.myblog.Util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.blog.Dao.LogDao;
/**
* 貌似目前所有邮箱都需要验证 故默认就是验证
* @author angel
*
*/
@Component
public class MailSender {
public static Session mailsession;
@Autowired
LogDao logdao;
public static String mailsender;
public void GetMailProperty(){
if(mailsession==null){
Properties props = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream("Mail.Properties");
try {
props.load(in);
in.close();
} catch (IOException e) {
logdao.insetlog(IDate.GetDate(), "读取Mail.Properties文件流失败");
e.printStackTrace();
}
mailsender = props.getProperty("userName");
MyAuthenticator authenticator =
new MyAuthenticator(props.getProperty("userName"),props.getProperty("passWord"));
mailsession = Session.getDefaultInstance(props, authenticator);
}
}
public boolean MailSend(String mailaddr,String head,String content){
//获取mailsession
GetMailProperty();
//创建邮件
Message msg = new MimeMessage(mailsession);
try {
//创建发件人
InternetAddress sender = new InternetAddress(mailsender);
//创建接受人
InternetAddress receiver = new InternetAddress(mailaddr);
msg.setFrom(sender);
msg.setRecipient(Message.RecipientType.TO, receiver);
} catch (MessagingException e) {
logdao.insetlog(IDate.GetDate(),"InternetAddress创建邮件接受或发件人失败");
e.printStackTrace();
return false;
}
try {
//邮件标题
msg.setSubject(head);
//邮件时间
msg.setSentDate(new Date());
//邮件内容
msg.setText(content);
Transport.send(msg);
} catch (MessagingException e) {
logdao.insetlog(IDate.GetDate(),"传输邮箱失败");
e.printStackTrace();
return false;
}
return true;
}
}
//用户验证
class IAuthenticator extends Authenticator {
String username = null;
String password = null;
public IAuthenticator() {
}
public IAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}