Spring提供了一个发送邮件的抽象层,使发送邮件实现非常简单。
下面代码需要mail.jar包,如果服务器需要认证,必须加入如下加粗代码:
源文件:SendMail.java:
package mail;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Date;
/**
* @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();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", protocol);
props.put("mail.from", fromMail);
//创建发送器
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(host);
sender.setUsername(username);
sender.setPassword(pass);
//创建消息
MimeMessage message = sender.createMimeMessage();
message.addHeader("X-Mailer", "Java Mailer");
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(sendTo);
helper.setFrom(fromMail, fromName);
helper.setSubject(subject);
helper.setText(msg);
helper.setSentDate(new Date());
//开始发送
sender.setJavaMailProperties(props);
sender.send(message);
}catch(Exception e){
System.out.println("Error:" + e);
return "Failure";
}
return "Success";
}
//测试
public static void main(String args[])throws Exception
{
String subject = "测试邮件";//标题
String sendTo = "[email protected]";//接收者邮件
String fromMail = "[email protected]";//发送者邮件
String user = "[email protected]";//发送者用户
String pw = "password";//发送者邮件密码
String fromName = "Chen";//发送者名字
String protocol = "smtp";//协议
String host = "smtp.my.com";//发送主机
String port = "25";//端口
String msg = "简单邮件发送。";//发送内容
String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port);
System.out.println("邮件发送结果:" + ret);
}
}
使用MimeMessageHelper,可以实现Multipart email,方便添加附件和内嵌资源等。