Android自动发送邮件

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Android⾃动发送邮件
本⽂简述的是在Android平台如何⾃动发送邮件(没有邮件编写界⾯),主要应⽤场景为忘记密码等安全等级较⾼的操作,⽐如我忘记密码了,点击“发送密码到我的邮箱”系统会将密码发送到注册时的电⼦邮件地址。

Android平台邮件客户端
Gmail: Gmai电⼦邮件客户端
Email: 通⽤的电⼦邮件客户端
解决⽅案
Gmail
Gmail已经⽀持⾃动发送了,所以⾮常简单。

在使⽤时,需要添加
<uses-permission android:name="com.google.android.gm.permission.AUTO_SEND" /> 到AndroidManifest.xml
⽰例代码如下:
Java代码
1. Intent intent = new Intent("com.google.android.gm.action.AUTO_SEND");
2. intent.setType("plain/text");
3. String[] reciver = new String[] { "xxxx@" };
4. String subject = "email title";
5. String body = "email body";
6. intent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver);
7. intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
8. intent.putExtra(android.content.Intent.EXTRA_TEXT, body);
Email
Email不⽀持⾃动发送,但⼜是默认邮件客户端,所以需要添加⾃动发送功能。

主要实现步骤为:
编写⼀个⾃动发送邮件类
主要功能为:接收⽤户输⼊,组装message对象,获取Sender实例,将message发送出去,最后删除message对象(这样已发送的邮件内容不会出现在client中,提⾼发安全性)
Java代码
1. package com.android.email.activity;
2.
3. import android.app.Activity;
4. import android.app.ProgressDialog;
5. import android.content.ContentUris;
6. import android.content.Context;
7. import android.content.Intent;
8. import android.os.AsyncTask;
9. import android.os.Bundle;
10. import android.text.TextUtils;
11. import android.util.Log;
12. import android.view.View;
13. import android.view.Window;
14. import .Uri;
15. import android.widget.Toast;
16.
17. import com.android.emailcommon.provider.EmailContent;
18. import com.android.emailcommon.provider.EmailContent.Account;
19. import com.android.emailcommon.provider.EmailContent.Message;
20. import com.android.emailcommon.mail.MessagingException;
21. import com.android.emailcommon.mail.Address;
22. import com.android.emailcommon.utility.Utility;
23. import com.android.emailcommon.mail.AuthenticationFailedException;
24. import com.android.email.EmailAddressValidator;
25. import com.android.email.mail.Sender;
26.
27. /**
28. * Send email in background with account configured in Email application.
29. * Sending message will not saved as draft or in out-going box. Usage:
30. *
31. * <pre>
32. * Intent intent = new Intent(&quot;com.android.email.intent.action.sendInBack&quot;);
33. * String[] reciver = new String[] { &quot;your_name@&quot; };
34. * String subject = &quot;email title&quot;;
35. * String body = &quot;email body &quot;;
36. * intent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver[0]);
37. * intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
38. * intent.putExtra(android.content.Intent.EXTRA_TEXT, body);
39. * startActivityForResult(Intent.createChooser(intent, &quot;send&quot;), 0x02);
40. * </pre>
41. *
42. * Now, attachment and multi-receiver function is unsupported.
43. *
44. * @author melord
45. *
46. */
47. public class EmailSendAutoActivity extends Activity implements SendListener {
48.
49. private static String tag = "EmailSendAutoAcitivity";
50. private Context mContext;
51.
52. private String mTo;
53. private String mCc;
54. private String mBcc;
55. private String mSubject;
56. private String mBody;
57.
58. private EmailAddressValidator mValidator = new EmailAddressValidator();
59. private SendListener mListener;
60. private Toast mWaiting;
61. private boolean enableLog = true;
62.
63. /**
64. * Sending account email address.
65. */
66. private String mSendEmail;
67. /**
68. * Sending account id
69. */
70. private long mAccountId = -1;
71.
72. @Override
73. protected void onCreate(Bundle savedInstanceState) {
74. super.onCreate(savedInstanceState);
75. this.mContext = this;
76. requestWindowFeature(Window.FEATURE_NO_TITLE);
77.
78. mListener = this;
79. Intent intent = getIntent();
80. initMessageFromIntent(intent);
81. initAccountFromIntent(intent);
82.
83. new SendTask().execute();
84. String msg = intent.getStringExtra("sendMsg");
85. if (msg == null) {
86. msg = "Sending message...";
87. }
88. // mWaiting = ProgressDialog.show(this, "", "sending...", true, true,
89. // null);
90. mWaiting = Toast.makeText(this, msg, Toast.LENGTH_LONG);
91. mWaiting.show();
92. }
93.
94. @Override
95. public void onBackPressed() {
96. if (mWaiting != null) {
97. mWaiting.cancel();
98. }
99. super.onBackPressed();
100. }
101.
102. @Override
103. public void finish() {
104. if (mWaiting != null) {
105. mWaiting.cancel();
106. }
107. super.finish();
108. }
109.
110. /**
111. * Initialize sending account from intent.
112. *
113. * @param intent
114. * imcoming intent
115. */
116. private void initAccountFromIntent(Intent intent) {
117. String email = intent.getStringExtra("sendAccount");
118. if (email != null) {
119. log(String.format("send email use account (%s) ", email)); 120. mSendEmail = email;
121. Long[] ids = EmailContent.Account.getAllAccountIds(this); 122. if (ids != null && ids.length > 0) {
123. for (int i = 0; i < ids.length; i++) {
124. EmailContent.Account temp = EmailContent.Account 125. .restoreAccountWithId(this, ids[i]);
126. if (temp != null && email.equals(temp.getEmailAddress())) { 127. log("valid account");
128. mAccountId = ids[i];
129. break;
130. }
131. }
132. }
133. }
134. }
135.
136. /**
137. * Initialize message from intent.
138. *
139. * @param intent
140. * intent
141. */
142. private void initMessageFromIntent(Intent intent) {
143. String to = intent.getStringExtra(Intent.EXTRA_EMAIL);
144. mTo = composeAddress(to);
145.
146. String cc = intent.getStringExtra(Intent.EXTRA_CC);
147. mCc = composeAddress(cc);
148.
149. String bcc = intent.getStringExtra(Intent.EXTRA_BCC);
150. mBcc = composeAddress(bcc);
151.
152. mSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT); 153.
154. mBody = intent.getStringExtra(Intent.EXTRA_TEXT);
155.
156. log("to:" + mTo);
157. log("cc:" + mCc);
158. log("bcc:" + mBcc);
159.
160. }
161.
162. /**
163. * change to stand email address reference to Rfc822
164. *
165. * @param address
166. * email address
167. * @return RFC822 format email address
168. */
169. private String composeAddress(String address) {
170. String addr = null;
171. if (!TextUtils.isEmpty(address)) {
172. Address[] addresses = Address.parse(address.trim());
173. addr = Address.pack(addresses);
174. }
175. return addr;
176. }
177.
178. /**
179. * Update message. fill fields.
180. *
181. * @param message
182. * email message
183. * @param account
184. * sending account
185. */
186. private void updateMessage(Message message, Account account) {
187. if (message.mMessageId == null || message.mMessageId.length() == 0) { 188. message.mMessageId = Utility.generateMessageId();
189. }
190. message.mTimeStamp = System.currentTimeMillis();
191. // it will : Name<Address>
192. message.mFrom = new Address(account.getEmailAddress(), account
193. .getSenderName()).pack();
194. message.mTo = mTo;
195. message.mCc = mCc;
196. message.mBcc = mBcc;
197. message.mSubject = mSubject;
198. message.mText = mBody;
199. message.mAccountKey = account.mId;
200. // here just used account setting simply
201. message.mDisplayName = account.getSenderName();
202. message.mFlagRead = true;
203. message.mFlagLoaded = Message.FLAG_LOADED_COMPLETE;
204.
205. }
206.
207. private void log(String msg) {
208. if (enableLog) {
209. Log.i(tag, msg);
210. }
211. }
212.
213. /**
214. * Really send message.
215. *
216. * @param account
217. * sending account
218. * @param messageId
219. * message id
220. */
221. public void sendMessage(Account account, long messageId) {
222. // message uri
223. Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, 224. messageId);
225. try {
226. // get a sender, ex. smtp sender.
227. Sender sender = Sender.getInstance(mContext, account
228. .getSenderUri(mContext));
229. // sending started
230. mListener.onStarted(account.mId, messageId);
231. // sending
232. sender.sendMessage(messageId);
233. // send completed
234. mListener.onCompleted(account.mId);
235.
236. } catch (MessagingException me) {
237. // report error
238. mListener.onFailed(account.mId, messageId, me);
239. } finally {
240. try {
241. // delete this message whenever send successfully or not 242. mContext.getContentResolver().delete(uri, null, null);
243. } catch (Exception ex) {
244. Log.w(tag, "delete message occur exception message uri:" + uri); 245. }
246. }
247. }
248.
249. public void onCompleted(long accountId) {
250. log("send mail ok");
251. // return Activity.RESULT_OK when send successfully
252. setResult(RESULT_OK);
253. finish();
254. }
255.
256. public void onFailed(long accountId, long messageId, Exception ex) { 257. log("send mail failed : " + ex.toString());
258. finish();
259. }
260.
261. public void onStarted(long messageId, long accountId) {
262. log("send mail started");
263. }
264.
265. /**
266. * Send message task, it is an async task
267. *
268. * @author melord_li
269. *
270. */
271. private class SendTask extends AsyncTask<Void, Void, Void> { 272. @Override
273. protected Void doInBackground(Void... params) {
274. // get default account, if not set, first record is treated as
275. // default.
276. // long id = Account.getDefaultAccountId(mContext);
277. long id = mAccountId;
278. if (id < 0) {
279. id = Account.getDefaultAccountId(mContext);
280. }
281. if (id < 0) {
282. Log.w(tag, "no account exists");
283. finish();
284. return null;
285. }
286. // get full account message
287. Account account = Account.restoreAccountWithId(mContext, id); 288.
289. // A empty message
290. Message message = new Message();
291. // fill message field
292. updateMessage(message, account);
293.
294. // Save this message. Because send API will read message in message
295. // db.
296. Uri uri = message.save(mContext);
297. if (uri == null) {
298. Log.e(tag, "save message occured an error");
299. finish();
300. return null;
301. }
302.
303. // send
304. sendMessage(account, message.mId);
305. return null;
306. }
307. }
308. }
309.
310. /**
311. * Sending monitor
312. *
313. * @author melord
314. *
315. */
316. interface SendListener {
317.
318. /**
319. * Send failed.
320. *
321. * @param accountId
322. * account id
323. * @param messageId
324. * message id
325. * @param ex
326. * exception
327. */
328. void onFailed(long accountId, long messageId, Exception ex);
329.
330. /**
331. * Send begin.
332. *
333. * @param accountId
334. * account id
335. * @param messageId
336. * message id
337. */
338. void onStarted(long messageId, long accountId);
339.
340. /**
341. * Send completed.
342. *
343. * @param accountId
344. * account id
345. */
346. void onCompleted(long accountId);
347. }
配置
Xml代码
1. <activity android:name=".activity.EmailSendAutoActivity" android:theme="@android:style/Theme.Translucent">
2. <intent-filter>
3. <action android:name="com.android.email.intent.action.sendInBack"/>
4. <data android:mimeType="*/*" />
5. <category android:name="android.intent.category.DEFAULT" />
6. </intent-filter>
7. </activity>
使⽤
Java代码
1. Intent intent = new Intent("com.android.email.intent.action.sendInBack");
2. String[] reciver = new String[] { "yourname@" };
3. String subject = "email title";
4. String body = "email body";
5. intent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver[0]);
6. intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
7. intent.putExtra(android.content.Intent.EXTRA_TEXT, body);
8.
9. startActivityForResult(Intent.createChooser(intent, "send"), 0x02);
处理回调
如果发送成功,会返回RESULT_OK。

-----摘⾃。

相关文档
最新文档