2005/10/28

[Info] JavaMail

Spring Framework also provide an abstract layer for JavaMail.
Here has a reference link:
Sending Email with Spring mail abstraction layer

Here has sample code which write by me:

package albert.guo.util;



import java.io.File;

import java.util.ArrayList;

import java.util.HashMap;



import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;



import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;

import org.springframework.mail.javamail.MimeMessageHelper;



/**

*

* @author Albert

*

*/

public class MailUtil {



private String addr[];

private String subject;

private String text;

private String host;

private String filepath;

private String filename;

private ArrayList fileList;



public MailUtil(String iAddr[], String iSubject, String iText, String iHost){

this.addr = iAddr;

this.subject = iSubject;

this.text = iText;

this.host = iHost;

}



public MailUtil(String iAddr[], String iSubject, String iText, String iHost,

ArrayList iFileList){

this.addr = iAddr;

this.subject = iSubject;

this.text = iText;

this.host = iHost;

this.fileList = iFileList;

}



/*

* 發送mail(不含附加檔案)

*/

public void sendMsg(){

SimpleMailMessage msg = new SimpleMailMessage();

msg.setTo(this.addr);

msg.setSubject(this.subject);

msg.setText(this.text);



JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

mailSender.setHost(this.host);

mailSender.send(msg);

}



/*

* 發送mail(含附加檔案)

*/

public void sendMsgAndAttachment(){

JavaMailSenderImpl sender = new JavaMailSenderImpl();

sender.setHost(this.host);



MimeMessage message = sender.createMimeMessage();



try {

//use the true flag to indicate you need a multipart message

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setTo(this.addr);

helper.setSubject(this.subject);

helper.setText(this.text);



for(int i=0; i<this.fileList.size(); i++){

HashMap attachment = (HashMap)fileList.get(i);

String filepath = (String)attachment.get("filepath");

String filename = (String)attachment.get("filename");

helper.addAttachment(filename, new File(filepath+filename));

}

sender.send(message);

} catch (MessagingException e) {

e.printStackTrace();

}

}



public static void main(String[] args) {

String addr[] = new String [] {"albertg@systex.com.tw"};

//MailUtil mailUtil = new MailUtil(addr, "標題", "內容\n啦啦啦", "mail.systex.com.tw");

//mailUtil.sendMsg();

ArrayList list = new ArrayList();

HashMap hm1 = new HashMap();

hm1.put("filepath", "C:/");

hm1.put("filename","test.doc");

HashMap hm2 = new HashMap();

hm2.put("filepath", "C:/");

hm2.put("filename", "LiveABC.Log");

list.add(hm1);

list.add(hm2);

MailUtil mailUtil = new MailUtil(addr, "標題", "內容\n啦啦啦", "mail.systex.com.tw",
list);

mailUtil.sendMsgAndAttachment();

}



}

 

No comments: