Android--email send mail, text and attachments form mail

Source: Internet
Author: User
Tags starttls

1. The first jar package is Javaemail

Https://yunpan.cn/cB3kY8WIvcGtU (Extract code: e042)

2. Tool Kit

Package Com.kllayhello.utils;import Android.content.context;import Android.content.intent;import Android.net.Uri; Import Android.util.log;import Java.util.properties;import Javax.activation.commandmap;import Javax.activation.datahandler;import Javax.activation.filedatasource;import Javax.activation.MailcapCommandMap; Import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.multipart;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 ; Import Javax.mail.internet.mimeutility;import javax.mail.util.bytearraydatasource;/** * Created by Administrator on 2016/6/30. * http://www.jb51.net/article/38158.htm * http://blog.csdn.net/svenke2011/article/details/8229521 */HTTP// blog.csdn.net/mad1989/article/details/25964495 * * http://blog.csdn.net/chinafe/article/details/7183400 *http:// Blog.csdn.net/xanxus46/article/details/8296529 * http://blog.csdn.net/kudy21/article/details/7665434 */public class emailutils{/** * Android inside Department Send mail * call Mobile email * cannot be sent automatically * sendto Send mail * */public void Sendtoemail (String title,string content,context        Context) {Intent data=new Intent (intent.action_sendto);        Data.setdata (Uri.parse ("mailto:[email protected]"));        Data.putextra (Intent.extra_subject, title);        Data.putextra (intent.extra_text, content);    Context.startactivity (data); * * * */public void Sendtofileemail (String title,string content,context Context) is not automatically sent/** * * * * Calling the Mobile mailbox for attachment        {Intent Intent = new Intent (intent.action_send);        String[] tos = {"[email protected]"};        String[] CCS = {"[email protected]"};        String[] BCCs = {"[email protected]"};        Intent.putextra (Intent.extra_email, TOS);        Intent.putextra (INTENT.EXTRA_CC, CCS);        Intent.putextra (INTENT.EXTRA_BCC, BCCs); IntEnt.putextra (intent.extra_text, content);        Intent.putextra (Intent.extra_subject, title);        Intent.putextra (Intent.extra_stream, Uri.parse ("File:///mnt/sdcard/qq.png"));        Intent.settype ("image/*");        Intent.settype ("message/rfc882");        Intent.createchooser (Intent, "Choose Email Client");    Context.startactivity (Intent);  * * * * * * * * * * * * * * * * Mail/** * * * @param host * Mail server such as: smtp.qq.com * @param     Address * e-mail addresses such as: [email protected] * @param from * from: [email protected] * @param password * Your email password * @param to * recipient * @param port * Port (QQ    : * @param subject * Email subject * @param content * Message content * @throws Exception */ public void SendEmail (string host, string address, string from, string password, string to, string port, String subject , String content) throws Exception {Multipart Multipart;        String finalstring = "";        Properties props = System.getproperties ();        Props.put ("Mail.smtp.starttls.enable", "true");        Props.put ("Mail.smtp.host", host);        Props.put ("Mail.smtp.user", address);        Props.put ("Mail.smtp.password", password);        Props.put ("Mail.smtp.port", port);        Props.put ("Mail.smtp.auth", "true");        LOG.I ("Check", "Done POPs");        Session session = Session.getdefaultinstance (props, null);        DataHandler handler = new DataHandler (New Bytearraydatasource (Finalstring.getbytes (), "Text/plain"));        MimeMessage message = new MimeMessage (session);        Message.setfrom (New InternetAddress (from));        Message.setdatahandler (handler);        LOG.I ("Check", "done Sessions");        MultiPart = new Mimemultipart ();        InternetAddress toaddress;        toaddress = new internetaddress (to);        Message.addrecipient (Message.RecipientType.TO, toaddress); LOG.I ("Check", "added Recipient ");        Message.setsubject (subject);        Message.setcontent (MultiPart);        Message.settext (content);        LOG.I ("Check", "Transport");        Transport Transport = Session.gettransport ("SMTP");        LOG.I ("Check", "Connecting");        Transport.connect (host, address, password);        LOG.I ("Check", "Wana send");        Transport.sendmessage (Message, message.getallrecipients ());        Transport.close ();    LOG.I ("Check", "sent");     /** * Send Attachment Mail * http://cuisuqiang.iteye.com/blog/1586023 * *//** * Mail Sender * * @param host * Mail server such as: smtp.qq.com * @param address * e-mail addresses such as: [email protected] * @param f            ROM * from: [email protected] * @param password * Your email password * @param to *     Recipient * @param port * Port (QQ:25) * @param subject * Email subject * @param content    * Email content * @throws Exception */public void Sendemailfile (string host, string address, string from, string password, string to, string port, string        Subject, String content,string File_path) throws Exception {Mimemultipart multiPart;        String finalstring = "";        Properties props = System.getproperties ();        Props.put ("Mail.smtp.starttls.enable", "true");        Props.put ("Mail.smtp.host", host);        Props.put ("Mail.smtp.user", address);        Props.put ("Mail.smtp.password", password);        Props.put ("Mail.smtp.port", port);        Props.put ("Mail.smtp.auth", "true");        Session session = Session.getdefaultinstance (props, null);        DataHandler handler = new DataHandler (New Bytearraydatasource (Finalstring.getbytes (), "Text/plain"));        MimeMessage message = new MimeMessage (session);        Message.setfrom (New InternetAddress (from));        Message.setdatahandler (handler); MultiPart = new Mimemultipart ("mixed");        Annex InternetAddress Toaddress; Toaddress= new InternetAddress (to);  Message.addrecipient (Message.RecipientType.TO, toaddress);        Add Recipient log.i ("Check", "added recipient");        Message.setsubject (subject);        Message content MimeBodyPart Htmlpart = new MimeBodyPart (); Htmlpart.setcontent ("<body background= ' # ' >" + "<div style= ' Position:absol Ute left:390px;  Top:150px;height: "+" 100px;width:200px; ' align= ' center ' > ' + ' <font        color= ' Red ' > This is a test email, do not reply </font> "+" </div></body> "," text/html;charset=utf-8 ");        The order of TODO assembly is very important, make sure to assemble the text field first, then assemble the file Multipart.addbodypart (Htmlpart);            Attachment Add try{mimebodypart Attachpart = new MimeBodyPart (); Filedatasource FDS = new Filedatasource (File_path);            Open the file you want to send DataHandler dh=new datahandler (FDS);            Attachpart.setdatahandler (DH); Attachpart.setfilename (MimeutiLity.encodetext (Dh.getname ())); Set name Multipart.addbodypart (Attachpart);  Add Attachment message.setcontent (MultiPart); Attachment settings Content message.savechanges ();        Save Message}catch (Exception e) {System.out.print ("File Bug:::" +e.getmessage ());        } Transport Transport = Session.gettransport ("SMTP");        Transport.connect (host, address, password);        Transport.sendmessage (Message, message.getallrecipients ());        Transport.close ();        LOG.I ("Check", "sent");    System.out.println ("Send success!"); }/** * Temporarily unavailable, time to study * Send the message to be attached *str_to_mail the destination of the email (to the recipient's mailbox) * Str_from_mail The origin of the e-mail (from the sender's mailbox) * STR_SMTP Host sender uses the e-mail sent    Mailbox Server * Str_user Sender user name * str_pass Sender Password * Str_title Message title * Str_body Message content * Str_file_path Attachment * */ public void Send_mail_file (String str_to_mail,string str_from_mail,string str_smtp,string str_user,string Str_pass,      String ports,string str_title,string str_body,string str_file_path) {  LOG.V ("Filesend", "send_mail_file");   String host = STR_SMTP;    Sender uses e-mail server String from = Str_from_mail;   Origin of Outgoing mail (sender's mailbox) String to = Str_to_mail;        e-mail Destination (recipient's mailbox) LOG.V ("Filesend", STR_SMTP);        LOG.V ("Filesend", Str_from_mail);        LOG.V ("Filesend", Str_to_mail);        Properties props = System.getproperties ();//Get System Properties Props.put ("Mail.smtp.starttls.enable", "true"); Props.put ("Mail.smtp.host", host);//Setup mail server//sender mailbox and password Props.put ("Mail.smtp.user", Str_use        R);        Props.put ("Mail.smtp.password", Str_pass);        Props.put ("Mail.smtp.port", ports); Props.put ("Mail.smtp.auth", "true");        This can be done by verifying session session = Session.getdefaultinstance (props, null); MimeMessage message = new MimeMessage (session); Define message try {message.setfrom (new internetaddress (from)),//Set the From address} catch (Messagingexception e) {E.priNtstacktrace ();            try {message.addrecipient (message.recipienttype.to,new internetaddress (to));//Set The To address Message.setsubject (str_title);//Set the subject Message.settext (str_body);//Set the content}        catch (Messagingexception e) {e.printstacktrace ();        } MimeBodyPart Attachpart = new MimeBodyPart (); Filedatasource FDS = new Filedatasource (Str_file_path);            Open the file you want to send the try {attachpart.setdatahandler (FDS) (new DataHandler);        Attachpart.setfilename (Fds.getname ());        } catch (Messagingexception e) {e.printstacktrace (); } Mimemultipart Allmultipart = new Mimemultipart ("mixed");            Attachment try {allmultipart.addbodypart (Attachpart);//Add message.setcontent (Allmultipart);        Message.savechanges ();        } catch (Messagingexception e) {e.printstacktrace ();   } try {//Error solving method         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);        Transport.send (message);//Start send} catch (Messagingexception e) {e.printstacktrace (); }    }}

 3. Using the toolkit:

  But_emailtest.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View V                ) {//Use Handlerthread mhandlerthread=new handlerthread ("Myhandlerthread");                 Mhandlerthread.start ();                Mhandler = new Handler (Mhandlerthread.getlooper ());            Mhandler.post (mrunnable);    }        }); } Runnable mrunnable = new Runnable () {@Override public void run () {networkutils nu=new NETW            Orkutils ();            Emailutils email=new emailutils ();            Emsuper.run (); Ail.sendtofileemail ("Hahaha test", "This is honor OH support you next haha", minshili.this);            String to= "[email protected]";            String host = "smtp.17xu.com"; String address = "[email protected]";            Sender address String from = "[email protected]";            string password = "******";//Password String filepath=nu.getsdpath () + "/" + "qq.png"; String port = "25"; Send the mail port number try {//email. SendEmail (host, address, from, password, to, port, "Subject test", "content oh hahaha haha");//Attachment email.            Sendemailfile (host, address, from, password, to, port, "Subject test", "content oh hahaha haha", filepath);            } catch (Exception e) {e.printstacktrace (); }        }    };

 4.sd Card Gets the file path, determines whether the network is linked

Package Com.kllayhello.utils;import Android.content.context;import Android.net.connectivitymanager;import Android.net.networkinfo;import android.os.environment;import java.io.file;/** * Created by Administrator on 2016/6/30.        */public class Networkutils {/** * Determines whether the network is linked * */public Boolean isnetworkconnected (context context) {                    if (context = null) {Connectivitymanager Mconnectivitymanager = (connectivitymanager) context            . Getsystemservice (Context.connectivity_service);            Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo ();            if (mnetworkinfo! = null) {return mnetworkinfo.isavailable ();    }} return false;        }/** * Determine if the SD card exists and gets the path * */public String Getsdpath () {File sddir = null; Boolean sdcardexist = Environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED);       /Determine if the SD card exists if (sdcardexist) {     Sddir = Environment.getexternalstoragedirectory ();//Get with Directory} return sddir.tostring (); }}

Reference files:

* http://cuisuqiang.iteye.com/blog/1586023

* http://www.jb51.net/article/38158.htm
* http://blog.csdn.net/svenke2011/article/details/8229521
*
* http://blog.csdn.net/mad1989/article/details/25964495
*
* http://blog.csdn.net/chinafe/article/details/7183400
*http://blog.csdn.net/xanxus46/article/details/8296529
* http://blog.csdn.net/kudy21/article/details/7665434

Android--email send mail, text and attachments form mail

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.