javaWEB郵件測試

新建一個工具類:html

Mail.javajava

該類的主要關鍵點是:一、設置系統屬性。也就是你是用什麼協議來進行郵件發送的,郵件協議有不少在種,好比impt,smpt,prop等協議,服務器

我如今測試用的是smpt協議,smpt協議裏也分爲不少種,覺得有不一樣的郵箱QQ,126,新浪等,因此就有不一樣的smpt系統屬性了(注:這些session

均可以再網上查到),我用的協議是smpt.qq.com,經過property將它存到map集合裏面:props.put("host","smpt.qq.com")eclipse

二、準備獲取郵件回話對象,經過mail.jar包中Session.getDefaultInstance()來獲取回話。工具

三、準備建立MIME郵件對象,jar包自帶的MimeMessage(session)方法測試

四、設置smtp身份認證:props.put("mail.smtp.auth", "true");ui

五、定義郵件主題:mimeMsg.setSubject(mailSubject);六、htm

六、定義郵件內容:bp.setContent("" + mailBody, "text/html;charset=GBK");對象

七、設置發信人:mimeMsg.setFrom(new InternetAddress(from));

八、定義收信人:mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

九、定義抄送人:mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress .parse(copyto));

如下是源碼:

package com.util;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail {
	private MimeMessage mimeMsg;
	private Session session;
	private Properties props;
	private Multipart mp;
	
	private static String smtp = "smtp.qq.com";// smtp服務器
	private static String from = "你的郵箱帳號@qq.com";// 郵件顯示名稱
	private static String copyto = "";// 抄送人郵件地址
	private static String subject = "找回密碼";// 郵件標題
	private static String username = "郵箱帳號";// 發件人真實的帳戶名
	private static String password = "密碼";// 發件人密碼
	
	public Mail(String smtp) {
		setSmtpHost(smtp);
		createMimeMessage();
	}
	public void setSmtpHost(String hostName) {
		System.out.println("設置系統屬性:mail.smtp.host=" + hostName);
		if (props == null) {
			props = System.getProperties();
		}
		props.put("mail.smtp.host", hostName);
	}
	public boolean createMimeMessage() {
		try {
			System.out.println("準備獲取郵件會話對象!");
			session = Session.getDefaultInstance(props, null);
		} catch (Exception e) {
			System.out.println("獲取郵件會話錯誤!" + e);
			return false;
		}
		System.out.println("準備建立MIME郵件對象!");
		try {
			mimeMsg = new MimeMessage(session);
			mp = new MimeMultipart();

			return true;
		} catch (Exception e) {
			System.out.println("建立MIME郵件對象失敗!" + e);
			return false;
		}
	}

	/*定義SMTP是否須要驗證*/
	public void setNeedAuth(boolean need) {
		System.out.println("設置smtp身份認證:mail.smtp.auth = " + need);
		if (props == null)
			props = System.getProperties();
		if (need) {
			props.put("mail.smtp.auth", "true");
		} else {
			props.put("mail.smtp.auth", "false");
		}
	}
	public void setNamePass(String name, String pass) {
		username = name;
		password = pass;
	}

	/*定義郵件主題*/
	public boolean setSubject(String mailSubject) {
		System.out.println("定義郵件主題!");
		try {
			mimeMsg.setSubject(mailSubject);
			return true;
		} catch (Exception e) {
			System.err.println("定義郵件主題發生錯誤!");
			return false;
		}
	}

	/*定義郵件正文*/
	public boolean setBody(String mailBody) {
		try {
			BodyPart bp = new MimeBodyPart();
			bp.setContent("" + mailBody, "text/html;charset=GBK");
			mp.addBodyPart(bp);
			return true;
		} catch (Exception e) {
			System.err.println("定義郵件正文時發生錯誤!" + e);
			return false;
		}
	}

	/*設置發信人*/
	public boolean setFrom(String from) {
		System.out.println("設置發信人!");
		try {
			mimeMsg.setFrom(new InternetAddress(from)); //發信人
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/*定義收信人*/
	public boolean setTo(String to) {
		if (to == null)
			return false;
		System.out.println("定義收信人!");
		try {
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/*定義抄送人*/
	public boolean setCopyTo(String copyto) {
		if (copyto == null)
			return false;
		try {
			mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress
					.parse(copyto));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/*發送郵件模塊*/
	public boolean sendOut() {
		try {
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			System.out.println("郵件發送中....");
			Session mailSession = Session.getInstance(props, null);
			Transport transport = mailSession.getTransport("smtp");
			transport.connect((String) props.get("mail.smtp.host"), username, password);
			transport.sendMessage(mimeMsg, mimeMsg
			.getRecipients(Message.RecipientType.TO));
			System.out.println("發送成功!");
			transport.close();
			return true;
		} catch (Exception e) {
			System.err.println("郵件失敗!" + e);
			return false;
		}
	}

	/*調用sendOut方法完成發送*/ 
	public static boolean sendAndCc(String to,String content) {
		Mail theMail = new Mail(smtp);
		theMail.setNeedAuth(true); // 驗證
		
		if (!theMail.setSubject(subject))
			return false;
		if (!theMail.setBody(content))
			return false;
		if (!theMail.setTo(to))
			return false;
		if (!theMail.setCopyTo(copyto))
			return false;
		if (!theMail.setFrom(from))
			return false;
		theMail.setNamePass(username, password);
		if (!theMail.sendOut())
			return false;
		return true;
	}
	
	
//	public static void main(String[] args) {
//			        String smtp = "smtp.qq.com";// smtp服務器
//			        String from = "郵箱帳號@.qq.com";// 郵件顯示名稱
//			        String to = "收件人帳號@qq.com";// 收件人的郵件地址,必須是真實地址
//			        String copyto = "";// 抄送人郵件地址
//			        String subject = "測試郵件";// 郵件標題
//			        String content = "你好!這是測試郵件,請不要回復";// 郵件內容
//			        String username = "你的郵箱帳號";// 發件人真實的帳戶名
//			        String password = "密碼";// 發件人密碼
//			        Mail.sendAndCc(smtp, from, to, copyto, subject, content, username, password);
//			    }
}

 以上代碼,通過測試,能夠運行成功。注意:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
當出現以上錯誤時,恭喜您已經離接收郵件不遠了,不然請您解決好全部的異常後再來看這個帖子。

javax.mail和javax.activation這兩個包已經在javaEE5當中屬於基礎包了,就是JDK中自帶了已經,可是裏面的方法與如今外面的mail.jar和activation.jar有一些出入,因此初學者在直接copy別人代碼的時候每每會出現上面的錯誤。
廢話很少說下面是解決方法
進到

X:\Program Files\MyEclipse 6.5\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_6.5.0.zmyeclipse650200806\data\libraryset\EE_5

這個路徑裏,能夠看到javaee.jar,用rar把這個文件打開,而後進到javax文件夾裏,刪除mail.jar和activation.jar(個人javaee.jar裏,這兩個東西是文件夾,總之刪掉就OK,不過要注意備份一下)

相關文章
相關標籤/搜索