當前位置:才華齋>IT認證>SUN認證>

Spring如何實現郵件傳送

SUN認證 閱讀(2.77W)

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,方便新增附件和內嵌資源等。