Spring提供了一个发送邮件的抽象层,使发送邮件实现非常简单。下面代码需要包,如果服务器需要认证,必须加入如下加粗代码:
源文件::
package mail;
import MailSenderImpl;
import MessageHelper;
import Message;
import erties;
import ;
/**
* @author chrischen
*/
public class SendMail {
//邮件发送器
public static String Sender(String subject, String msg, String sendTo, String fromMail, String user, String pw, String fromName, String protocol, String host, String port){
try{
final String username = user;
final String pass = pw;
//需要认证
Properties props = new Properties();
(“”, host);
(“”, “true”);
(“ocol”, protocol);
(“”, fromMail);
//创建发送器
JavaMailSenderImpl sender = new JavaMailSenderImpl();
ost(host);
sername(username);
assword(pass);
//创建消息
MimeMessage message = teMimeMessage();
eader(“X-Mailer”, “Java Mailer”);
MimeMessageHelper helper = new MimeMessageHelper(message);
o(sendTo);
rom(fromMail, fromName);
ubject(subject);
ext(msg);
entDate(new Date());
//开始发送
avaMailProperties(props);
(message);
}catch(Exception e){
tln(“Error:” + e);
return “Failure”;
}
return “Success”;
}
//测试
public static void main(String args[])throws Exception
{
String subject = “测试邮件”;//标题
String sendTo = ”;//接收者邮件
String fromMail = ”;//发送者邮件
String user = ”;//发送者用户
String pw = “password”;//发送者邮件密码
String fromName = “Chen”;//发送者名字
String protocol = “smtp”;//协议
String host = “”;//发送主机
String port = “25”;//端口
String msg = “简单邮件发送。”;//发送内容
String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port);
tln(“邮件发送结果:” + ret);
}
}
使用MimeMessageHelper,可以实现Multipart email,方便添加附件和内嵌资源等。