1. 程式人生 > >javamail實現用普通QQ郵箱傳送郵件

javamail實現用普通QQ郵箱傳送郵件

本人最近在寫一個Android專案,使用者註冊的時候想用郵箱驗證的方式,於是就需要在伺服器端傳送電子郵件給新註冊使用者,郵件內容中包含一個 連結, 當用戶點選這個連結將 登入到伺服器 的驗證邏輯。本人在網上找了很多程式碼,可能由於是很久以前的了,各大郵箱的規範 什麼的都發生改變,所以總是出現一些問題。慶幸 的是,最後還是實現了。

這是我用大號 發給小號 和另外一個 163 郵箱的 測試郵件
這裡寫圖片描述

首先,發一個連線,我在困擾了了兩天之後,終於得到了這位前輩的解救,我發的程式碼基本上也都是他的原始碼,只是有幾處關鍵地方的改動。
點選
當然,把前輩的程式碼 copy 直接執行肯定是不行的。
廢話不說,直接上原始碼吧:

1、傳送郵件的類:

package com.pleasurewithriding.assistantclass;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import
javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import
javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class SendMail { private String username = null; private String password = null; private Authenticator auth = null; private MimeMessage mimeMessage =null; private Properties pros = null; private Multipart multipart = null; private BodyPart bodypart= null; /** * 初始化賬號密碼並驗證 * 建立MimeMessage物件 * 傳送郵件必須的步驟:1 * @param username * @param password */ public SendMail(String username,String password){ this.username = username; this.password = password; } /** * 初始化MimeMessage物件 * 傳送郵件必須的步驟:3 */ public void initMessage(){ this.auth = new Email_Autherticator(); Session session = Session.getDefaultInstance(pros,auth); session.setDebug(true); //設定獲取 debug 資訊 mimeMessage = new MimeMessage(session); } /** * 設定email系統引數 * 接收一個map集合key為string型別,值為String * 傳送郵件必須的步驟:2 * @param map */ public void setPros(Map<String,String> map){ pros = new Properties(); for(Map.Entry<String,String> entry:map.entrySet()){ pros.setProperty(entry.getKey(), entry.getValue()); } } /** * 驗證賬號密碼 * 傳送郵件必須的步驟 * @author Administrator * */ public class Email_Autherticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } /** * 設定傳送郵件的基本引數(去除繁瑣的郵件設定) * @param sub 設定郵件主題 * @param text 設定郵件文字內容 * @param rec 設定郵件接收人 * @throws MessagingException * @throws UnsupportedEncodingException */ public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{ mimeMessage.setSubject(sub); mimeMessage.setText(text); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec)); mimeMessage.setSentDate(new Date()); mimeMessage.setFrom(new InternetAddress(username,username)); } /** * 設定主題 * @param subject * @throws MessagingException */ public void setSubject(String subject) throws MessagingException{ mimeMessage.setSubject(subject); } /** * 設定日期 * @param date * @throws MessagingException */ public void setDate(Date date) throws MessagingException{ mimeMessage.setSentDate(new Date()); } /** * 設定郵件文字內容 * @param text * @throws MessagingException */ public void setText(String text) throws MessagingException{ mimeMessage.setText(text); } /** * 設定郵件頭部 * @param arg0 * @param arg1 * @throws MessagingException */ public void setHeader(String arg0,String arg1) throws MessagingException{ mimeMessage.setHeader(arg0, arg1); } /** * 設定郵件接收人地址 <單人傳送> * @param recipient * @throws MessagingException */ public void setRecipient(String recipient) throws MessagingException{ mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } /** * 設定郵件接收人地址 <多人傳送> * @param list * @throws MessagingException * @throws AddressException */ public String setRecipients(List<String> recs) throws AddressException, MessagingException{ if(recs.isEmpty()){ return "接收人地址為空!"; } for(String str:recs){ mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str)); } return "加入接收人地址成功!"; } /** * 設定郵件接收人地址 <多人傳送> * @param StringBuffer<parms,parms2,parms.....> * @throws MessagingException * @throws AddressException */ @SuppressWarnings("static-access") public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{ if(sb==null||"".equals(sb)){ return "字串資料為空!"; } Address []address = new InternetAddress().parse(sb.toString()); mimeMessage.addRecipients(Message.RecipientType.TO, address); return "收件人加入成功"; } /** * 設定郵件傳送人的名字 * @param from * @throws UnsupportedEncodingException * @throws MessagingException */ public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{ mimeMessage.setFrom(new InternetAddress(username,from)); } /** * 傳送郵件<單人傳送> * return 是否傳送成功 * @throws MessagingException */ public String sendMessage() throws MessagingException{ Transport.send(mimeMessage); return "success"; } /** * 設定附件 * @param file 傳送檔案的路徑 */ public void setMultipart(String file) throws MessagingException, IOException{ if(multipart==null){ multipart = new MimeMultipart(); } multipart.addBodyPart(writeFiles(file)); mimeMessage.setContent(multipart); } /** * 設定附件<新增多附件> * @param fileList<接收List集合> * @throws MessagingException * @throws IOException */ public void setMultiparts(List<String> fileList) throws MessagingException, IOException{ if(multipart==null){ multipart = new MimeMultipart(); } for(String s:fileList){ multipart.addBodyPart(writeFiles(s)); } mimeMessage.setContent(multipart); } /** * 傳送文字內容,設定編碼方式 * <方法與傳送附件配套使用> * <傳送普通的文字內容請使用setText()方法> * @param s * @param type * @throws MessagingException */ public void setContent(String s,String type) throws MessagingException{ if(multipart==null){ multipart = new MimeMultipart(); } bodypart = new MimeBodyPart(); bodypart.setContent(s, type); multipart.addBodyPart(bodypart); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); } /** * 讀取附件 * @param filePath * @return * @throws IOException * @throws MessagingException */ public BodyPart writeFiles(String filePath)throws IOException, MessagingException{ File file = new File(filePath); if(!file.exists()){ throw new IOException("檔案不存在!請確定檔案路徑是否正確"); } bodypart = new MimeBodyPart(); DataSource dataSource = new FileDataSource(file); bodypart.setDataHandler(new DataHandler(dataSource)); //檔名要加入編碼,不然出現亂碼 bodypart.setFileName(MimeUtility.encodeText(file.getName())); return bodypart; } }

2、測試類:

package com.pleasurewithriding.assistantclass;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;

public class TestSend
{

    public static void main(String[] args) throws MessagingException, IOException
    {

        Map<String,String> map= new HashMap<String,String>();
        ***SendMail mail = new SendMail("QQ號@qq.com","**你的授權碼***");***
        map.put("mail.smtp.host", "smtp.qq.com");

        //暫時未成功,需要除錯
        /*SendMail mail = new SendMail("14789****@sina.cn","***miya");
        map.put("mail.smtp.host", "smtp.sina.com");*/
        map.put("mail.smtp.auth", "true");
        *****map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        map.put("mail.smtp.port", "465");
        map.put("mail.smtp.socketFactory.port", "465");*****
        mail.setPros(map);
        mail.initMessage();
        /*
         * 新增收件人有三種方法:
         * 1,單人新增(單人傳送)呼叫setRecipient(str);傳送String型別
         * 2,多人新增(群發)呼叫setRecipients(list);傳送list集合型別
         * 3,多人新增(群發)呼叫setRecipients(sb);傳送StringBuffer型別
         */
        List<String> list = new ArrayList<String>();
        list.add("****@qq.com");
        //list.add("***[email protected]");
        list.add("****@163.com");
        mail.setRecipients(list);
        /*String defaultStr = "[email protected],[email protected],[email protected],[email protected];
        StringBuffer sb = new StringBuffer();
        sb.append(defaultStr);
        sb.append(",[email protected]");
        mail.setRecipients(sb);*/
        mail.setSubject("測試郵箱");
        //mail.setText("謝謝合作");
        mail.setDate(new Date());
        mail.setFrom("MY");
//      mail.setMultipart("D:你你你.txt");
        mail.setContent("謝謝合作", "text/html; charset=UTF-8");
        /*List<String> fileList = new ArrayList<String>();
        fileList.add("D:1.jpg");
        fileList.add("D:activation.zip");
        fileList.add("D:dstz.sql");
        fileList.add("D:軟體配置要求.doc");
        mail.setMultiparts(fileList);*/
        System.out.println(mail.sendMessage());
    }

}

程式碼中斜體加粗的地方就是我的改動:
1、建構函式初始化郵箱地址和密碼的地方,前輩用的是163郵箱,我沒去測試163郵箱了,直接用QQ郵箱了,但是要注意 QQ郵箱的密碼不是你的 郵箱獨立密碼,當然更不是QQ密碼,而是郵箱授權碼,我之前在網上搜了很多文章,由於時間較早,都是用的郵箱獨立密碼(那時候騰訊還沒有搞出授權碼這個東西)測試成功,這個造成了我一時的困擾。不知道163郵箱是不是也出了授權碼的概念,如果是,那麼估計也是要用授權碼代替密碼吧,有興趣的可以自己去測試。關於QQ郵箱授權碼的獲取,
進入QQ郵箱=》設定=》賬戶,在開啟幾個服務三方服務的時候,會要求獲取授權碼:
這裡寫圖片描述

2、現在的QQ郵箱要求 使用 SSL 連線,當我把前輩的程式碼直接執行的時候,丟擲了異常,叫什麼 “530 Error: A secure connection is requiered(such as ssl)”,然後在網上找了別人的程式碼,發現加了這幾句(我還沒有去細究,等專案做完再說),
map.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
map.put(“mail.smtp.port”, “465”);
map.put(“mail.smtp.socketFactory.port”, “465”);
3、如果你想看到 javamail 執行的 過程,加上 session.setDebug(true),我的原始碼裡面已經加上了。

我的原始碼檔案就不上了,因為所有程式碼都貼上來了,直接 copy 就可以的,好了,就說這麼多,希望對跟我一樣的小白有點幫助

相關推薦

javamail實現普通QQ郵箱傳送郵件

本人最近在寫一個Android專案,使用者註冊的時候想用郵箱驗證的方式,於是就需要在伺服器端傳送電子郵件給新註冊使用者,郵件內容中包含一個 連結, 當用戶點選這個連結將 登入到伺服器 的驗證邏輯。本人在網上找了很多程式碼,可能由於是很久以前的了,各大郵箱的規範

django實現如何向QQ郵箱傳送郵件

首先在settings中進行設定以下操作: 首先是:EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend',確保你使用的是smtp 接著設定一下操作: EMAIL_HOST = 'smtp.qq.c

Java 基於JavaMail實現QQ郵箱傳送郵件

需求 最近專案在做新聞爬蟲,想實現這個功能:爬蟲某個頁面失敗後,把這個頁面的 url 發到筆者的郵箱。最終實現的效果圖如下,後期可以加上過濾標籤、失敗狀態碼等,方便分類搜尋異常。 開發人員可以根據郵件裡的 url 和堆疊資訊,分析爬蟲失敗的原因。 是

flask_email實現QQ郵箱傳送郵件

直接上程式碼 from flask import Flask from flask_mail import Mail, Message from threading import Thread #

PythonQQ郵箱傳送郵件時授權碼問題

QQ郵箱最新推出了一個授權碼,需已驗證的手機號向QQ郵箱伺服器傳送一條簡訊獲得。該授權碼用於第三方客戶端登入,代替了第三方登入時使用的個人郵箱密碼。 在測試過程中遇到兩個問題: 1.提示需建立SSL安全連線。於是將smtplib.SMTP() 改成了smtplib.SMT

python怎麼qq郵箱傳送郵件

使用SSL的通用配置如下: 接收郵件伺服器:pop.qq.com ,使用SSL,埠 995 傳送郵件伺服器: smtp.qq.com,使用SSL,埠 465或 587 賬戶名:QQ郵箱賬戶名(不用加“@qq.com”) 步驟一: 去設定-->賬戶-》找到POP3/IM

Springboot2.0.4呼叫qq郵箱傳送郵件

開場白:沒記錯的話,用不同框架開發一個發郵箱的功能,都會遇到多多少少的問題,這次也不能例外,否則就沒有意義了。 今天用springboot2.0.4開發發郵件功能,遇到了以下三個坑 專案中添加了該依賴,但是仍舊找不到 下面的物件,一直說該物件沒有被發現,後來

CI框架中QQ郵箱傳送郵件

public function qq(){       $this->load->library('email');       $config['protocol'] = 'smtp';

Python SMTP模組使用QQ郵箱傳送郵件

前言:    嘗試實現《Python程式設計快速上手  讓繁瑣工作自動化》書籍中的第十六章習題部分,使用python傳送email資訊,嘗試傳送Html,附件和正文都同時存在的郵件,使用QQ郵箱,最終實現根據表格標記對不同使用者發不同郵件功能。(根據之前編寫的讀取表格示例可以

java程式碼使用QQ郵箱傳送郵件

import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.

阿里雲上的使用QQ郵箱傳送郵件

直接上程式碼了 由於阿里雲禁用了25埠所以替換成465埠並修改協議為ssl才能傳送郵件 參考我的另一篇部落格 http://blog.csdn.net/u013412790/article/details/54912506 public class Se

Java使用QQ郵箱傳送郵件

本文介紹通過java,使用QQ郵箱進行傳送郵件。 首先要開啟郵箱的SMTP服務,騰訊會給一個授權碼。 package util; import java.util.Properties; import javax.mail.Authenticator; import

Spring Boot學習(十四)之Spring boot中使用QQ郵箱傳送郵件

相信使用過Spring的眾多開發者都知道Spring提供了非常好用的JavaMailSender介面實現郵件傳送。在Spring Boot的Starter模組中也為此提供了自動化配置。下面通過例項看看如

python 3.6.3 , 使用QQ 郵箱傳送郵件

示例程式碼:#coding=utf-8 import smtplib from email.mime.text import MIMEText msg_from='[email protec

MATLAB實現給指定郵箱傳送郵件

此處以163郵箱為例,當然用qq郵箱也是如法炮製。 一、前期準備條件是要開啟163郵箱的smtp服務,步驟如下: 1、點選右上角的“設定”選項,然後點選“POP3/SMTP/IMAP”選項,開啟smtp服務: 2、點選“客戶端授權密碼”選項,然後根據提示來獲取客

java 程式碼實現163郵箱傳送郵件QQ郵箱

1.建立一個使用者類,來接收發送郵件的郵箱地址和授權密碼(需要注意的是,這裡的密碼不是正常使用郵箱的登陸密碼,而是客戶端生成的另一個專門的授權碼   ,這裡需要開啟相應的傳送郵件的服務,這裡開啟的是pop3/smtp服務)package appsoft.cd.applicat

java實現通過QQ郵箱傳送啟用郵件 springBoot

使用者郵件啟用 通過QQ郵箱傳送啟用郵件 soringBoot 本文主要介紹了使用java 呼叫郵箱傳送郵件的功能 首先新建一個springboot專案  pom依賴如下 <parent> <groupId>org.springframewor

C# qq郵箱郵件

use ssa ring auth param com fault set mage 一、在企業的QQ郵箱中開啟POP3/SMTP服務 開啟服務時,授權密碼保存好。 二、示例 public static string UserName = ""; // 企業郵箱

linuxmail往qq郵箱郵件

因為qq郵箱的一些安全設定,本機用mail命令投遞的郵件 smtp伺服器用的是localhost的sendmail或者postfix 所以郵件的from是來自localhost.localdomain郵件 qq一律拒之! 並且返回550錯誤 此處配置mail命令使用遠端的

實現使用者在網頁中給我的QQ郵箱郵件

我們在設計網站的時候,有時候會需要收集使用者的反饋,這個時候就要在網站中加入給我寫郵件的功能。、 本文介紹如何利用QQ郵箱的“郵我”功能給我發郵件,方法其實很簡單哦: 1.訪問http://open.mail.qq.com; 2.點選“獲取郵我按鈕”(如果沒有登入QQ郵箱需