android 發送QQ郵箱


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendQQMailUtil {

public static void main(String[] args) throws AddressException,MessagingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 連接協議
properties.put("mail.smtp.host", "smtp.qq.com");// 主機名
properties.put("mail.smtp.port", 465);// 端口號
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");// 設置是否使用ssl安全連接 ---一般都使用
properties.put("mail.debug", "true");// 設置是否顯示debug信息 true 會在控制台顯示相關信息
// 得到回話對象
Session session = Session.getInstance(properties);
// 獲取郵件對象
Message message = new MimeMessage(session);
// 設置發件人郵箱地址
message.setFrom(new InternetAddress("xxx@qq.com"));
// 設置收件人郵箱地址
message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")});
//message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));//一個收件人
// 設置郵件標題
message.setSubject("xmqtest");
// 設置郵件內容
message.setText("郵件內容郵件內容郵件內容xmqtest");
// 得到郵差對象
Transport transport = session.getTransport();
// 連接自己的郵箱賬戶
transport.connect("xxx@qq.com", "xxxxxxxxxxxxx");// 密碼為QQ郵箱開通的stmp服務后得到的客戶端授權碼
// 發送郵件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}

 

以上代碼來自:https://www.cnblogs.com/xmqa/p/8458300.html

 

這段代碼  用單純的java程序直接就可以用了  但是在android中  transport.connect() 這一句會出錯  因為android不支持在主線程中有網絡連接操作  所以要新建一個線程進行操作 

還有163郵箱的服務  但是還沒有試

但是出現錯誤:Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1

原因:465端口是為SMTPS(SMTP-over-SSL)協議服務開放的,這是SMTP協議基於SSL安全協議之上的一種變種協議。

解決:加上如下代碼

    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

解決方法來源:https://blog.csdn.net/u012424783/article/details/79429621

過程中我還遇到過兩個問題  一個報錯:Program type already present......

這個是引用了兩個相同的但是名字不同的第三方jar包  去掉一個就好了  

還有一個問題報錯:missing INTERNET permission  這個是沒有給網絡訪問權限   需要在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET" />  就可以了

剛搞安卓沒幾天  好多事情都不懂  嘻嘻


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM