Java認證考試:Spring實現郵件發送
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,方便添加附件和內嵌資源等。