所需jar包:comment-email.jar mail.jar activation.jar
一、 配置QQ郵箱的IMAP
進入qq電子郵件點擊 設置->賬戶里開啟 SMTP 服務(開啟IMAP/SMTP服務) 注意:在啟用QQ郵箱的14天之后才能開啟此服務
開啟之后會得到授權碼,此授權碼要記住或者保存到文本文件當中發送郵件的時候需要作為驗證密碼使用。
二.使用JavaMail發送一封簡單郵件 的示例代碼:
public static void main(String[] args) throws Exception{ // 不要使用SimpleEmail,會出現亂碼問題 HtmlEmail email = new HtmlEmail(); try { // 這里是SMTP發送服務器的名字:,普通qq號只能是smtp.qq.com ;smtp.exmail.qq.com沒測試成功 email.setHostName("smtp.qq.com");
//設置需要鑒權端口 email.setSmtpPort(465);
//開啟 SSL 加密 email.setSSLOnConnect(true); // 字符編碼集的設置 email.setCharset("utf-8"); // 收件人的郵箱 email.addTo("xxxxx@qq.com"); // 發送人的郵箱 email.setFrom("xxxxx@qq.com", "(發件人名稱)"); // 如果需要認證信息的話,設置認證:用戶名-密碼。分別為發件人在郵件服務器上的注冊名稱和得到的授權碼 email.setAuthentication("xxxxx@qq.com", "授權碼"); email.setSubject("下午3:00會議室討論,請准時參加"); // 要發送的信息,由於使用了HtmlEmail,可以在郵件內容中使用HTML標簽 email.setMsg("郵件內容"); // 發送 email.send(); System.out.println ( "郵件發送成功!" ); } catch (EmailException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println ( "郵件發送失敗!" ); } }
二. 示例代碼2:
public static void main2() throws Exception { Properties props = new Properties(); // 開啟debug調試 props.setProperty("mail.debug", "true"); // 發送服務器需要身份驗證 props.setProperty("mail.smtp.auth", "true"); // 設置郵件服務器主機名 props.setProperty("mail.host", "smtp.qq.com"); // 發送郵件協議名稱 props.setProperty("mail.transport.protocol", "smtp"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getInstance(props); Message msg = new MimeMessage(session); msg.setSubject("主題"); StringBuilder builder = new StringBuilder(); builder.append("胡子&小猿的博客:"); builder.append("url = " + "http://www.cnblogs.com/hzxy-blog/"); msg.setText(builder.toString()); msg.setFrom(new InternetAddress("**發送人的郵箱地址**
")); Transport transport = session.getTransport(); transport.connect("smtp.qq.com","**發送人的郵箱地址**"
,
"**你的郵箱密碼或者授權碼**"
); transport.sendMessage(msg, new Address[] { new InternetAddress("**接收人的郵箱地址**"
) }); transport.close(); }