Android Send mail

Source: Internet
Author: User

Some of the key logs in the project need to be taken from the customer, in order to facilitate the collection of logs in the client to join the mail send function (although the use of sharing features can also send mail, the premise needs to login to the mobile phone's mailbox, more trouble, but also into the page, the user experience is not very good).

The main implementation of the Send mail, cc, send attachments function

First Look at:


Involves 3 jars and encapsulated interfaces

Jemailhelper.java
Package Jwzhangjie.com.javaemail;import Android.os.asynctask;import Java.util.date;import java.util.List;import Java.util.properties;import Javax.activation.commandmap;import Javax.activation.mailcapcommandmap;import Javax.mail.authenticator;import Javax.mail.message;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;/** * Created by Zhangjie on 15/8/31.  */public class Jemailhelper {private int port = 553; The SMTP protocol uses the port private String host = "smtp.163.com";   Sender mail server private String user = "*******@163.com"; User account private String password = "********";    User password private list<string> emailtos;    Private list<string> Emailccs;    Private String subject;    Private String body;    private list<string> paths; Enum SenDstatus {sending, UNDO, Sendok, sendfail};    Private Sendstatus Sendstatus;        public interface Jieemailinfterface {void Startsend ();    void Sendstatus (Sendstatus sendstatus);    } private Jieemailinfterface Jieemailinfterface; public void Setjieemailinfterface (Jieemailinfterface jieemailinfterface) {this.jieemailinfterface = JieEmailInfter    Face    } public Jemailhelper () {sendstatus = Sendstatus.undo; }//Construct the server, port, account, Password public jemailhelper (string host, int port, string user, string password) of the sending mail account {This.por        t = port;        This.user = user;        This.password = password;        This.host = host;    Sendstatus = Sendstatus.undo;     }/** * @param emailtos main recipient's e-mail list * @param emailccs cc person's email list * @param subject Message title * @param body Body content * @param paths sent attachment path collection */public void SetParams (list<string> emailtos, list<string> E Mailccs, string subject, String body,                          list<string> paths) {this.emailtos = Emailtos;        This.emailccs = Emailccs;        This.subject = subject;        This.body = body;    This.paths = paths;    } public void SendEmail () {new Jieasyntask (). Execute ();        } private void Sendemailbg () throws Exception {Properties properties = new Properties ();        Properties.put ("Mail.smtp.host", host);        Properties.put ("Mail.smtp.port", port);        Properties.put ("Mail.smtp.auth", "true");//true must be quoted Properties.put ("Mail.transport.protocol", "SMTP");        Jieauthenticator Jieauth = new Jieauthenticator (user, password);        Session session = Session.getinstance (properties, Jieauth);        Create a message mimemessage msg = new MimeMessage (session);        Set Sender Msg.setfrom (new internetaddress);            Set Primary receiver if (Emailtos! = null &&!emailtos.isempty ()) {int size = Emailtos.size (); InternetaddresS[] addresses = new internetaddress[size];            for (int i = 0; i < size; i++) {addresses[i] = new InternetAddress (Emailtos.get (i));        } msg.setrecipients (Message.RecipientType.TO, addresses);             }//Set CC person's e-mail if (Emailccs! = null &&!emailccs.isempty ()) {int size = Emailccs.size ();            Internetaddress[] addresses = new internetaddress[size];            for (int i = 0; i < size; i++) {addresses[i] = new InternetAddress (Emailccs.get (i));        } msg.setrecipients (Message.RecipientType.CC, addresses);        } msg.setsubject (subject);        Create a message body mimebodypart Msgbodypart = new MimeBodyPart ();        Msgbodypart.settext (body);        Create Multipart to add additional parts Multipart MP = new Mimemultipart ();        Mp.addbodypart (Msgbodypart);    Create file attachment for (String path:paths) {MimeBodyPart Filebodypart = new MimeBodyPart ();        Filebodypart.attachfile (path);        Mp.addbodypart (Filebodypart);        }//Add multipart to the message body in Msg.setcontent (MP);        Set Date msg.setsentdate (new date ());        Set the attachment format 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);    Send Message Transport.send (msg);        } class Jieauthenticator extends Authenticator {private String struser;        Private String strpwd; Public JieauthenticaTor (string user, string password) {this.struser = user;        this.strpwd = password; } protected Passwordauthentication Getpasswordauthentication () {return new passwordauthentication (Strus        Er, strpwd); }} class Jieasyntask extends Asynctask<void, void, sendstatus> {@Override protected void Onpre            Execute () {super.onpreexecute ();            if (jieemailinfterface! = null) {jieemailinfterface.startsend (); }} @Override protected void OnPostExecute (sendstatus result) {Super.onpostexecute (Result            );            if (jieemailinfterface! = null) {Jieemailinfterface.sendstatus (result);        } sendstatus = Sendstatus.undo;  } @Override protected Sendstatus doinbackground (Void ... params) {try {Sendstatus                = sendstatus.sending;                SENDEMAILBG (); SenDstatus = Sendstatus.sendok;                } catch (Exception e) {e.printstacktrace ();            Sendstatus = Sendstatus.sendfail;        } return sendstatus; }    }}

Package Jwzhangjie.com.javaemail;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.widget.toast;import Java.util.arraylist;import Java.util.list;public class Javaemailactivity extends    Activity {Jemailhelper helper;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_java_email);    Helper = new Jemailhelper ();        public void SendMail (view view) {list<string> files = new arraylist<string> ();        Files.add ("/mnt/sdcard/test.txt");        list<string> toemail = new arraylist<string> ();        Toemail.add ("[email protected]");        list<string> ccemail = new arraylist<string> ();        Ccemail.add ("1067***** @qq. com");        Ccemail.add ("352**** @qq. com"); Helper.setparams (Toemail, Ccemail, "Android Send Test Mail", "Dear all: This is a test mail!        ", files); Helper.setjieemailinfterface (New JEmailhelper.jieemailinfterface () {@Override public void Startsend () {showinfo ("Start send            Mail "); } @Override public void Sendstatus (Jemailhelper.sendstatus sendstatus) {switch (send                        Status) {case sendok:showinfo ("Send mail Success");                    Break                        Case Sendfail:showinfo ("Failed to send mail");                    Break                        Case Sending:showinfo ("the message is being sent, please retry later");                Break        }            }        });    Helper.sendemail ();    The public void Showinfo (String msg) {Toast.maketext (Getapplicationcontext (), MSG, Toast.length_short). Show (); }}
Address of three jars:
Http://pan.baidu.com/s/1bnbi7zp

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Send mail

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.