- package example;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeUtility;
- import org.apache.commons.mail.Email;
- import org.apache.commons.mail.EmailAttachment;
- import org.apache.commons.mail.EmailException;
- import org.apache.commons.mail.HtmlEmail;
- import org.apache.commons.mail.MultiPartEmail;
- public class SendMail3 {
- public void sendMail() throws AddressException,EmailException {
- try {
- Email htmlEmail = new HtmlEmail();
- // STMP服務器
- htmlEmail.setHostName("smtp.sina.com.cn");
- htmlEmail
- .setAuthentication("[email protected]", "wswlyn841013");
- htmlEmail.addTo("[email protected]");
- List list = new ArrayList();
- // throw AddressException
- list.add(new InternetAddress("[email protected]"));
- list.add(new InternetAddress("[email protected]"));
- htmlEmail.setTo(list);
- // addTo(String email),就是向一個List添加email,
- // setTo(list)是批量添加email
- htmlEmail.setFrom("[email protected]");
- htmlEmail.setCharset("GBK");
- htmlEmail.setSubject("email 測試");
- htmlEmail.setMsg("email 測試");
- htmlEmail.send();
- System.out.println("end");
- } catch (EmailException e) {
- e.printStackTrace();
- }
- }
- public void sendEmailAttachment() throws UnsupportedEncodingException {
- EmailAttachment attachment = new EmailAttachment();
- attachment.setPath("D:\\eBook\\CSS.chm");
- attachment.setDisposition(EmailAttachment.ATTACHMENT);
- attachment.setDescription("Picture of John");//附件描述
- attachment.setName("CSS.chm");// 名字必須帶文件擴展名
- attachment.setName(MimeUtility.encodeText("需傳送的附件.txt"));
- // HtmlEmail hemail=new HtmlEmail();爲MultiPartEmail子類
- // hemail.attach(attachment);
- MultiPartEmail email = new MultiPartEmail();
- email.setCharset("GBK");
- email.setHostName("smtp.sina.com.cn");
- email.setAuthentication("[email protected]", "wswlyn841013");
- try {
- email.addTo("[email protected]", "martin");
- email.setFrom("[email protected]", "martin");
- email.setSubject("郵件主題");
- email.setMsg("郵件內容");
- //中文:將setMsg替換爲setContent()
- email.setContent("This is a simple test of commons-email", "text/plain;charset=GBK");
- // add attachment
- email.attach(attachment);
- email.send();
- System.out.println("end");
- } catch (EmailException e) {
- e.printStackTrace();
- }
- }
- }
commons-email筆記
java 代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.