1 public class ApacheMailTest { 2 // smtp服務(wù)器 3 private String hostName = "smtp.qq.com"; 4 // 帳號(hào)與密碼 5 private String userName = "779554589"; 6 private String password = "這是個(gè)秘密"; 7 // 發(fā)件人 8 private String fromAddress = "779554589@qq.com"; 9 // 發(fā)件人姓名 10 private String fromName = "loadfate"; 11 12 public static void main(String[] args) throws Exception { 13 // 收件人與收件人名字 14 String toAddress = "loadfate@163.com"; 15 String toName = "loadfate"; 16 ApacheMailTest test = new ApacheMailTest(); 17 // 所有的異常都為處理,方便瀏覽 18 19 test.sendSimpleEmail(toAddress, toName); 20 test.sendHtmlEmail(toAddress, toName); 21 test.sendMultiPartEmail(toAddress, toName); 22 System.out.println("發(fā)送完成"); 23 } 24 25 // 發(fā)送簡單郵件,類似一條信息 26 public void sendSimpleEmail(String toAddress, String toName) throws Exception { 27 SimpleEmail email = new SimpleEmail(); 28 email.setHostName(hostName);// 設(shè)置smtp服務(wù)器 29 email.setAuthentication(userName, password);// 設(shè)置授權(quán)信息 30 email.setCharset("utf-8"); 31 email.setFrom(fromAddress, fromName, "utf-8");// 設(shè)置發(fā)件人信息 32 email.addTo(toAddress, toName, "utf-8");// 設(shè)置收件人信息 33 email.setSubject("測試主題");// 設(shè)置主題 34 email.setMsg("這是一個(gè)簡單的測試!");// 設(shè)置郵件內(nèi)容 35 email.send();// 發(fā)送郵件 36 } 37 38 // 發(fā)送Html內(nèi)容的郵件 39 public void sendHtmlEmail(String toAddress, String toName) throws Exception { 40 HtmlEmail email = new HtmlEmail(); 41 email.setHostName(hostName); 42 email.setAuthentication(userName, password); 43 email.setCharset("utf-8"); 44 email.addTo(toAddress, toName, "utf-8"); 45 email.setFrom(fromAddress, fromName, "utf-8"); 46 email.setSubject("這是一個(gè)html郵件"); 47 // 設(shè)置html內(nèi)容,實(shí)際使用時(shí)可以從文本讀入寫好的html代碼 48 email.setHtmlMsg("<div style='width:100px;height:200px;'>a</div>"); 49 email.send(); 50 51 } 52 53 // 發(fā)送復(fù)雜的郵件,包含附件等 54 public void sendMultiPartEmail(String toAddress, String toName) throws Exception { 55 MultiPartEmail email = null; 56 email = new MultiPartEmail(); 57 email.setHostName(hostName); 58 email.setAuthentication(userName, password); 59 email.setCharset("utf-8"); 60 email.addTo(toAddress, toName, "utf-8"); 61 email.setFrom(fromAddress, fromName, "utf-8"); 62 email.setSubject("這是有附件的郵件"); 63 email.setMsg("<a href='#'>測試內(nèi)容</a>"); 64 65 // 為郵件添加附加內(nèi)容 66 EmailAttachment attachment = new EmailAttachment(); 67 attachment.setPath("D:\\郵件.txt");// 本地文件 68 // attachment.setURL(new URL("http://xxx/a.gif"));//遠(yuǎn)程文件 69 attachment.setDisposition(EmailAttachment.ATTACHMENT); 70 attachment.setDescription("描述信息"); 71 // 設(shè)置附件顯示名字,必須要編碼,不然中文會(huì)亂碼 72 attachment.setName(MimeUtility.encodeText("郵件.txt")); 73 // 將附件添加到郵件中 74 email.attach(attachment); 75 email.send(); 76 } 77 } |