我知道可以調用系統發送郵件,但這種方法有個弊端,就是您的手機必須安裝mail的用戶端,
是以我想不用系統發送郵件這種方式,能不能向任意郵箱發送郵件呢?給我自己丢下了一個命題。
于是我調查,發現smtp發送email 無需系統支援,無需配置,
經過多次嘗試,多次失敗,終于完成了此項功能。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmLqNjezcnM5xGOx1mM0MnazRDN1EjMx8CX1AzLcJTMzEDMy8CXtVncvZ2LcRnbl1GajFGd0F2LcFGdhR2Lc12bj5yc1J2awFmL3d3dvw1LcpDc0RHaiojIsJye.jpg)
填寫您的郵箱、密碼等,我就能收到您的回報意見,是不是很友善呢,
此貼,講這個功能給扣出來了,并附上其他的兩種方法發送郵件。
效果圖如下:
1、使用mail用戶端發送郵件
這種方法前提您的手機必須安裝mail用戶端,您可以測試的時候下載下傳qq郵箱用戶端,看看運作的效果。
case r.id.button1:
// 建立intent
intent emailintent = new intent(android.content.intent.action_send);
// 設定内容類型
emailintent.settype("plain/text");
// 設定額外資訊
emailintent.putextra(android.content.intent.extra_email,
new string[] { "收件人郵箱" });// 比如qq郵箱,測試的時候可以手機安裝qq郵箱用戶端
emailintent.putextra(android.content.intent.extra_subject, "主題");
emailintent.putextra(android.content.intent.extra_text, "内容");
// 啟動activity
startactivity(intent.createchooser(emailintent, "發送郵件..."));
break;
複制代碼
2、使用smtp發送郵件
這是此貼的重點所在,smtp的全稱是“simple mail transfer protocol”,即簡單郵件傳輸協定。
它是一組用于從源位址到目的位址傳輸郵件的規範,通過它來控制郵件的中轉方式。
smtp 協定屬于 tcp/ip 協定簇,它幫助每台計算機在發送或中轉信件時找到下一個目的地。
smtp 伺服器就是遵循 smtp 協定的發送郵件伺服器。
下載下傳後複制libs,即可。
下面介紹兩種方法實作使用smtp發送郵件
(1)方法一
case r.id.button2:
new thread() {
@override
public void run() {
emailsender sender = new emailsender();
// 設定伺服器位址和端口,網上搜的到
sender.setproperties("smtp.qq.com", "465");
// 分别設定發件人,郵件标題和文本内容
try {
sender.setmessage("發件人郵箱", "主題主題1", "内容内容1");
sender.setreceiver(new string[] { "收件人郵箱" });
sender.sendemail("smtp.qq.com", "發件人郵箱", "發件人郵箱密碼");
} catch (addressexception e) {
e.printstacktrace();
log.e("wxl", "addressexception", e);
} catch (messagingexception e) {
log.e("wxl", "messagingexception", e);
}
}
}.start();
這裡需要emailsender.java
package com.xiaomolong.example.smtpmail;
import java.io.file;
import java.util.date;
import java.util.properties;
import javax.activation.datahandler;
import javax.activation.filedatasource;
import javax.mail.address;
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.mimebodypart;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
public class emailsender {
private properties properties;
private session session;
private message message;
private mimemultipart multipart;
public emailsender() {
super();
this.properties = new properties();
}
public void setproperties(string host, string post) {
// 位址
this.properties.put("mail.smtp.host", host);
// 端口号
this.properties.put("mail.smtp.post", post);
// 是否驗證
this.properties.put("mail.smtp.auth", true);
this.session = session.getinstance(properties);
this.message = new mimemessage(session);
this.multipart = new mimemultipart("mixed");
/**
* 設定收件人
*
* @param receiver
* @throws messagingexception
*/
public void setreceiver(string[] receiver) throws messagingexception {
address[] address = new internetaddress[receiver.length];
for (int i = 0; i < receiver.length; i++) {
address[i] = new internetaddress(receiver[i]);
}
this.message.setrecipients(message.recipienttype.to, address);
* 設定郵件
* @param from
* 來源
* @param title
* 标題
* @param content
* 内容
* @throws addressexception
public void setmessage(string from, string title, string content)
throws addressexception,
messagingexception {
this.message.setfrom(new internetaddress(from));
this.message.setsubject(title);
// 純文字的話用settext()就行,不過有附件就顯示不出來内容了
mimebodypart textbody = new mimebodypart();
textbody.setcontent(content, "text/html;charset=gbk");
this.multipart.addbodypart(textbody);
* 添加附件
* @param filepath
* 檔案路徑
public void addattachment(string filepath) throws messagingexception {
filedatasource filedatasource = new filedatasource(new file(filepath));
datahandler datahandler = new datahandler(filedatasource);
mimebodypart mimebodypart = new mimebodypart();
mimebodypart.setdatahandler(datahandler);
mimebodypart.setfilename(filedatasource.getname());
this.multipart.addbodypart(mimebodypart);
* 發送郵件
* @param host
* 位址
* @param account
* 賬戶名
* @param pwd
* 密碼
public void sendemail(string host, string account, string pwd)
throws messagingexception {
// 發送時間
this.message.setsentdate(new date());
// 發送的内容,文本和附件
this.message.setcontent(this.multipart);
this.message.savechanges();
// 建立郵件發送對象,并指定其使用smtp協定發送郵件
transport transport = session.gettransport("smtp");
// 登入郵箱
transport.connect(host, account, pwd);
// 發送郵件
transport.sendmessage(message, message.getallrecipients());
// 關閉連接配接
transport.close();
}
(2)方法二
case r.id.button3:
new sendtask().execute();
class sendtask extends asynctask<integer, integer, string> {
// 後面尖括号内分别是參數(例子裡是線程休息時間),進度(publishprogress用到),傳回值 類型
@override
protected void onpreexecute() {
// 第一個執行方法
super.onpreexecute();
protected string doinbackground(integer... params) {
// contact, contactpsw, title, content;
string isok = "";
mails m = new mails("發件人郵箱", "發件人郵箱密碼");
m.set_debuggable(false);
string[] toarr = { "收件人郵箱" };
m.set_to(toarr);
m.set_from("發件人郵箱");
m.set_subject("主題主題2");
m.setbody("内容内容2");
try {
// m.addattachment("/sdcard/filelocation");
if (m.send()) {
isok = "ok";
} else {
isok = "no";
} catch (exception e) {
log.e("wxl", "could not send email", e);
}
return isok;
protected void onprogressupdate(integer... progress) {
// 這個函數在doinbackground調用publishprogress時觸發,雖然調用時隻有一個參數
// 但是這裡取到的是一個數組,是以要用progesss[0]來取值
// 第n個參數就用progress[n]來取值
super.onprogressupdate(progress);
protected void onpostexecute(string result) {
// doinbackground傳回時觸發,換句話說,就是doinbackground執行完後觸發
// 這裡的result就是上面doinbackground執行後的傳回值,是以這裡是"執行完畢"
// settitle(result);
if ("ok".equals(result)) {
toast.maketext(getapplicationcontext(), "發送成功",
toast.length_short).show();
} else {
toast.maketext(getapplicationcontext(), "發送失敗",
super.onpostexecute(result);
這裡需要mails.java
import javax.activation.commandmap;
import javax.activation.datasource;
import javax.activation.mailcapcommandmap;
import javax.mail.bodypart;
import javax.mail.multipart;
import javax.mail.passwordauthentication;
public class mails extends javax.mail.authenticator {
private string _user;
private string _pass;
private string[] _to;
private string _from;
private string _port;
private string _sport;
private string _host;
private string _subject;
private string _body;
private boolean _auth;
private boolean _debuggable;
private multipart _multipart;
public mails() {
_host = "smtp.qq.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username _pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new mimemultipart(); // there is something wrong with
// mailcap, javamail can not find a
// handler for the multipart/mixed
// part, so this bit needs to be
// added.
mailcapcommandmap mc = (mailcapcommandmap) commandmap
.getdefaultcommandmap();
mc.addmailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addmailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addmailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addmailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addmailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
commandmap.setdefaultcommandmap(mc);
public string get_user() {
return _user;
public void set_user(string _user) {
this._user = _user;
public string get_pass() {
return _pass;
public void set_pass(string _pass) {
this._pass = _pass;
public string[] get_to() {
return _to;
public void set_to(string[] _to) {
this._to = _to;
public string get_from() {
return _from;
public void set_from(string _from) {
this._from = _from;
public string get_port() {
return _port;
public void set_port(string _port) {
this._port = _port;
public string get_sport() {
return _sport;
public void set_sport(string _sport) {
this._sport = _sport;
public string get_host() {
return _host;
public void set_host(string _host) {
this._host = _host;
public string get_subject() {
return _subject;
public void set_subject(string _subject) {
this._subject = _subject;
public string get_body() {
return _body;
public void set_body(string _body) {
this._body = _body;
public boolean is_auth() {
return _auth;
public void set_auth(boolean _auth) {
this._auth = _auth;
public boolean is_debuggable() {
return _debuggable;
public void set_debuggable(boolean _debuggable) {
this._debuggable = _debuggable;
public multipart get_multipart() {
return _multipart;
public void set_multipart(multipart _multipart) {
this._multipart = _multipart;
public mails(string user, string pass) {
this();
_user = user;
_pass = pass;
public boolean send() throws exception {
properties props = _setproperties();
if (!_user.equals("") && !_pass.equals("") && _to.length > 0
&& !_from.equals("") && !_subject.equals("")
&& !_body.equals("")) {
session session = session.getinstance(props, this);
mimemessage msg = new mimemessage(session);
msg.setfrom(new internetaddress(_from));
internetaddress[] addressto = new internetaddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressto[i] = new internetaddress(_to[i]);
msg.setrecipients(mimemessage.recipienttype.to, addressto);
msg.setsubject(_subject);
msg.setsentdate(new date()); // setup message body
bodypart messagebodypart = new mimebodypart();
messagebodypart.settext(_body);
_multipart.addbodypart(messagebodypart); // put parts in message
msg.setcontent(_multipart); // send email
transport.send(msg);
return true;
} else {
return false;
public void addattachment(string filename) throws exception {
bodypart messagebodypart = new mimebodypart();
datasource source = new filedatasource(filename);
messagebodypart.setdatahandler(new datahandler(source));
messagebodypart.setfilename(filename);
_multipart.addbodypart(messagebodypart);
@override
public passwordauthentication getpasswordauthentication() {
return new passwordauthentication(_user, _pass);
private properties _setproperties() {
properties props = new properties();
props.put("mail.smtp.host", _host);
if (_debuggable) {
props.put("mail.debug", "true");
if (_auth) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketfactory.port", _sport);
props.put("mail.smtp.socketfactory.class",
"javax.net.ssl.sslsocketfactory");
props.put("mail.smtp.socketfactory.fallback", "false");
return props;
} // the getters and setters
public string getbody() {
public void setbody(string _body) {
} // more of the getters and setters 锟斤拷.. }
代碼粘完了,這裡采用了線程和異步,對于新手可以學學。【賤泰迪】采用的是第二種方法。
下面開始說一下注意點:
首先加上聯網的權限,<uses-permission android:name="android.permission.internet" />,這是小問題
以上代碼完成沒有問題,但是運作會抛這樣的異常:
這是為什麼,使用smtp來發送e-mail,是以您的郵箱必須開啟此項服務,
【qq郵箱】【設定】【賬戶】【pop3/imap/smtp/exchange/carddav/caldav服務】如下圖:
最後附上下載下傳位址:http://download.csdn.net/detail/xiangzhihong8/6661655