Use javamail in Android to send emails with group attachments (absolutely available !)

Source: Internet
Author: User

I wrote an article about sending emails in Android, which uses an implicit intent to activate the built-in email sending function.

Today, it took me a day to implement this email sending function (mainly because the code on the internet is too pitfall ...)

Here, Gmail is used as the sender's mailbox. Other Netease And Sina should also be OK. QQ does not seem to work.

Resource from: javamail-android

The following are the implementation steps and related code.

Add a jar package to the Project

Put activation. jar, additionnal. jar, and mail. jar in the libs folder of the project. Select the three packages in the project, right-click and choose build path> Add to buildpath.

After the project is successfully added, it is like this.

Add mail class to project

package com.example.mailtest;import java.util.Date; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.MailcapCommandMap; import javax.mail.BodyPart; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class Mail 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 Mail() { _host = "smtp.gmail.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 Mail(String user, String pass) { this(); _user = user; _pass = pass; } public void setTo(String[] toArr) {this._to = toArr;}public void setFrom(String string) {this._from = string;}public void setSubject(String string) {this._subject = string;}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() { return _body; } public void setBody(String _body) { this._body = _body; } // more of the getters and setters ….. } 

Mailactivity call

Package COM. example. mailtest; import Java. util. properties; import javax. mail. address; import javax. mail. message; import javax. mail. session; import javax. mail. transport; import javax. mail. internet. internetaddress; import javax. mail. internet. mimemessage; import android. OS. asynctask; import android. OS. bundle; import android. OS. handler; import android. app. activity; import android. app. progressdialog; import android. Util. log; import android. view. menu; import android. view. view; import android. widget. button; import android. widget. toast; public class mailactivity extends activity {private button sendbtn; private string username; private string password; private handler sendhandler; private progressdialog; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcont Entview (R. layout. activity_mail); sendbtn = (button) findviewbyid (R. id. btnsend); sendhandler = new handler (); sendbtn. setonclicklistener (new view. onclicklistener () {public void onclick (view v) {sendtask stask = new sendtask (); stask.exe cute () ;}}) ;}@ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). inflate (R. menu. activity_mail, menu); Return true;} class sendtask extends asynctask <integer, integer, string> {// The parameters (in this example, thread rest time) are in the brackets ), progress (used by publishprogress), return value type @ override protected void onpreexecute () {// the first execution method toast. maketext (getapplicationcontext (), "begin send! ", Toast. length_short ). show (); super. onpreexecute () ;}@ override protected string doinbackground (integer... params) {// The second execution method, after onpreexecute () is executed // todo auto-generated method stub mail M = new mail ("empty.shen@gmail.com ", "*****"); string [] toarr = {"silangquan@gmail.com", "k283228391@126.com"}; M. setto (toarr); M. setfrom ("wooo@wooo.com"); M. setsubject ("javamailtest"); M. setbody ("email body. "); try {// if you want add attachment use function addattachment. // M. addattachment ("/sdcard/filelocation"); If (M. send () {system. out. println ("email was sent successfully. ");} else {system. out. println ("email was not sent. ") ;}} catch (exception e) {// toast. maketext (mailapp. this, "there was a problem sending the email. ", toast. length_long ). show (); log. E ("mailapp", "cocould not send email", e);} return "" ;}@ override protected void onprogressupdate (integer... progress) {// This function is triggered when doinbackground calls publishprogress. Although there is only one parameter during the call, // here an array is obtained, so you must use progesss [0] to set the value // the nth parameter uses progress [N] to set the value to super. onprogressupdate (Progress) ;}@ override protected void onpostexecute (string R) {// triggered when doinbackground is returned, in other words, it is triggered after doinbackground is executed. // The result here is the returned value after doinbackground is executed. Therefore, the result is "executed" // settitle (result); super. onpostexecute (r );}}}

Asynctask is used here. It should be connected to the Internet directly in the UI thread, or android. OS. networkonmainthreadexception is thrown.


Layout File

The layout file on the main interface is very simple.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MailActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="@string/hello_world" />    <Button        android:id="@+id/btnSend"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginTop="19dp"        android:text="Send" /></RelativeLayout>

Running effect:

After clicking send

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.