項目用到一需求,完成特定任務後需要自動發郵件給客戶,看了下javamail比較簡單...不囉嗦,你懂的,然後就開始寫寫個簡單的入門,先百度找到
mail.jar ,commons-email-X.X.jar ,activation.jar 這三個jar,放進項目裡
先寫個簡單的mail對象
package com.shadow.mvc.vo;import java.io.Serializable;/** * Mail屬性實體 * * @author shadow * */@SuppressWarnings("serial")public class Mail implements Serializable {public static final String ENCODEING = "UTF-8";private String host; // 伺服器位址private String sender; // 寄件者的郵箱private String receiver; // 收件者的郵箱private String name; // 寄件者暱稱private String username; // 帳號private String password; // 密碼private String subject; // 主題private String message; // 資訊(支援HTML)public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getSender() {return sender;}public void setSender(String sender) {this.sender = sender;}public String getReceiver() {return receiver;}public void setReceiver(String receiver) {this.receiver = receiver;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
然後就寫個工具類
package com.shadow.extras.util;import org.apache.commons.mail.EmailException;import org.apache.commons.mail.HtmlEmail;import org.apache.log4j.Logger;import com.shadow.mvc.vo.Mail;/** * 郵件發送工具實作類別 * * @author shadow * @create 2013/07/12 */public class MailUtil {protected final Logger logger = Logger.getLogger(getClass());public boolean send(Mail mail) {// 發送emailHtmlEmail email = new HtmlEmail();try {// 這裡是SMTP發送伺服器的名字:163的如下:"smtp.163.com"email.setHostName(mail.getHost());// 字元編碼集的設定email.setCharset(Mail.ENCODEING);// 收件者的郵箱email.addTo(mail.getReceiver());// 發送人的郵箱email.setFrom(mail.getSender(), mail.getName());// 如果需要認證資訊的話,設定認證:使用者名稱-密碼。分別為寄件者在郵件伺服器上的註冊名稱和密碼email.setAuthentication(mail.getUsername(), mail.getPassword());// 要發送的郵件主題email.setSubject(mail.getSubject());// 要發送的資訊,由於使用了HtmlEmail,可以在郵件內容中使用HTML標籤email.setMsg(mail.getMessage());// 發送email.send();if (logger.isDebugEnabled()) {logger.debug(mail.getSender() + " 發送郵件到 " + mail.getReceiver());}return true;} catch (EmailException e) {e.printStackTrace();logger.info(mail.getSender() + " 發送郵件到 " + mail.getReceiver()+ " 失敗");return false;}}}
最後寫個main方法測試下
public static void main(String[] args) {Mail mail = new Mail();mail.setHost("smtp.163.com"); // 設定郵件伺服器,如果不用163的,自己找找看相關的mail.setSender("shadowsick@163.com");mail.setReceiver("shadowsick@163.com"); // 接收人mail.setUsername("shadowsick@163.com"); // 登入帳號,一般都是和郵箱名一樣吧mail.setPassword("xxxxx"); // 寄件者郵箱的登入密碼mail.setSubject("aaaaaaaaa");mail.setMessage("bbbbbbbbbbbbbbbbb");new MailUtil().send(mail);}
最後看看效果