Organize several ways to send emails in the background of Android

Source: Internet
Author: User
Tags auth mixed rfc822 sessions mailmessage

Android Background email (without intent)





The Android SDK makes it easy to send e-mail from one application, but only through the intent approach, through the built-in mail application. This can satisfy most of the requirements, but if you want to send in the background, you can't.


In this article, I'll show you how to send an email in the background without user intervention.





First you need to download a special version of the JavaMail API, which is written specifically for Android.





Http://code.google.com/p/javamail-android/downloads/list








If you are blocked by the wall, you can also go here to download, the inside of the attachment contains all the things you need, including how to use in the activity of the Android application:








Let's get started, here is the encapsulation of the message delivery feature, which makes it easy to send e-mail and even add attachments.





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 don't 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 Boolean send () throws Exception {


Properties props = _setproperties ();





if (!_user.equals ("") &&!_pass.equals ("") && _to.length > 0 &&!_from.equals ("") &&! _subject.equals ("") &&!_body.equals ("")) {


Session sessions = 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


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 .....


}





And now I ' m going to go through each bit of code








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 don't 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;


}





In this code, we initialize the Class mail property and set it to the default value.


In addition, the JavaMail MIME type inside should be noted. There is an explanatory note in it.


The two 2 constructors inside are also carefully read, and you can go through one of the user names and passwords.





public Boolean send () throws Exception {


Properties props = _setproperties ();





if (!_user.equals ("") &&!_pass.equals ("") && _to.length > 0 &&!_from.equals ("") &&! _subject.equals ("") &&!_body.equals ("")) {


Session sessions = 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


Msg.setcontent (_multipart);





Send email


Transport.send (msg);





return true;


} else {


return false;


}


}





This is the sending method, which has the data attribute set, and then performs the send operation.








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);


}





This is a function to add an attachment, but it needs to be called before it is sent.








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;


}





Here, we set the properties of the mail authentication-The default is SMTP authentication.


This is all Gmail (google) SMTP server connection.








Android background Send Message collection apply exception information








This article is a practical article and will not involve too much theoretical analysis. The main is to let everyone look at the future know how to add this function in their own applications. The following appendix demo and key code is CSDN above an example code, I only have the package link and the interface changed, easy to read. So don't know who the original author of this demo is, if you see this is your demo code, please contact me to add your information.





(PS: New QQ Group, interested to join together to discuss: Android Group: 322599434)





1. Third Party Library





This time send the background mail need to use three third party's library, these several libraries in Java inside should be more famous. Used to be a friend of Java Mail development, should be used more or less. Android default to send mail method, need to call the system via intent mail program, this is not practical for our background operation.





Activation.jar


Additionnal.jar


Mail.jar





Below I demo example inside will enclose these three packages, these several packs on-line also many resources, may download by oneself.











2, Mail information





Because we are sending mail in the background, we need to collect some necessary information because the user is not required to enter this information.





Edited by Mythou


http://www.cnblogs.com/mythou/





public class Mailsenderinfo


{


IP and port of the server that sent the message


Private String Mailserverhost;


Private String Mailserverport = "25";





Address of the sender of the message


Private String fromaddress;


Address of the Mail recipient


Private String toaddress;


User name and password for the login mail sending server


Private String UserName;


private String password;


Whether authentication is required


Private Boolean validate = true;


Message subject


Private String subject;


Text content of a message


Private String content;


File name of the message attachment


Private string[] attachfilenames;


}





These are all the information we need to send emails. It should be noted here that we send background mail need to give the account password and other sensitive information. These email messages, we can write in the program, so that when we send the mail, we do not need users to enter any information.











3. Send mail





Edited by Mythou


http://www.cnblogs.com/mythou/





public boolean sendtextmail (Mailsenderinfo mailinfo)


{


To determine whether an identity certificate is required


Myauthenticator authenticator = null;


Properties Pro = Mailinfo.getproperties ();


if (Mailinfo.isvalidate ())


{


If authentication is required, create a password validator


Authenticator = new Myauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());


}


Constructs a session that sends a message based on the message conversation properties and the password validator


Session sendmailsession = Session.getdefaultinstance (pro,authenticator);


Try


{


Create a mail message based on session


Message MailMessage = new MimeMessage (sendmailsession);


Create Mail Sender Address


Address from = new InternetAddress (mailinfo.getfromaddress ());


Set the sender of a mail message


Mailmessage.setfrom (from);


Create the recipient address of the message and set it to the mail message


Address to = new InternetAddress (mailinfo.gettoaddress ());


Mailmessage.setrecipient (message.recipienttype.to,to);


Set the subject of a mail message


Mailmessage.setsubject (Mailinfo.getsubject ());


Set when mail messages are sent


Mailmessage.setsentdate (New Date ());


Set the main contents of a mail message


String mailcontent = Mailinfo.getcontent ();


Mailmessage.settext (mailcontent);


Send mail


Transport.send (MailMessage);


return true;


}


catch (Messagingexception ex)


{


Ex.printstacktrace ();


}


return false;


}





Send mail is mainly using the Mail.jar package inside the method, first of all, will use Myauthenticator class to judge some user authentication information, and then is to set up the message we collected above, and finally call the Transport.send () method to send us a set of good mail.





With me my personal test results, I was using QQ mailbox test, send the speed quickly, call the Send interface, basic immediately can receive mail. The demo provided below is also based on QQ mailbox, you can modify some of the mailbox parameters (SMTP, port and other information) to send to other mailbox servers. Using this method, I can send the exception information collected to our designated mailboxes by combining the previous article that collects the exception information of the program.





Finally, the point is that if you are directly in the background to send mail, it is best to give the user a hint, or let the user choose whether to send. Otherwise easy to back up rogue software or the background stolen traffic, O (∩_∩) o ha! Also need to pay attention to send the message frequency, avoid sending too frequently, the mail service provider has blocked your mail.





Android background Send mail class share





public class SendEmail {


private static final String TAG = "SendEmail";


To send an email address


Private String mailTo = null;


Mail Send Source Address


Private String mailfrom = null;


SMTP Host Address


Private String smtphost = null;


Whether to enable debugging


Private Boolean debug = false;





Private String Messagebasepath = null;


Email subject


Private String subject;





public void Setmailto (String mailTo) {


This.mailto = MailTo;


}





public void Setmailfrom (String mailfrom) {


This.mailfrom = Mailfrom;


}





public void Setsmtphost (String smtphost) {


This.smtphost = SMTPHost;


}





public void Setdebug (Boolean debug) {


This.debug = Debug;


}





public void Setmessagebasepath (String messagebasepath) {


This.messagebasepath = Messagebasepath;


}





public void Setsubject (String subject) {


This.subject = subject;


}





public void Setmsgcontent (String msgcontent) {


This.msgcontent = msgcontent;


}





public void Setattachedfilelist (Vector attachedfilelist) {


This.attachedfilelist = attachedfilelist;


}





public void Setemailaccount (String emailaccount) {


This.emailaccount = Emailaccount;


}





public void Setemailpwd (String emailpwd) {


This.emailpwd = emailpwd;


}





public void Setmessagecontenttype (String messagecontenttype) {


This.messagecontenttype = Messagecontenttype;


}





public void Setemailbccto (String emailbccto) {


This.emailbccto = Emailbccto;


}





public void Setemailccto (String emailccto) {


This.emailccto = Emailccto;


}





Email content


Private String msgcontent;





Private Vector attachedfilelist;


Private String emailaccount = null;


Private String emailpwd = null;


Private String Messagecontenttype = "Text/html;charset=utf-8";





Private String emailbccto = null;


Private String emailccto = null;





/*


Default constructor


*/


Public SendEmail () {


Super ();


}





private void Writeemail (session sessions, message message) throws Messagingexception {


String FileName;


Multipart Multipart = new Mimemultipart ();


Set Sender Address


if (Mailfrom!= null) {


Message.setfrom (New InternetAddress (Mailfrom));


LOG.I (TAG, "sender email Address:" + mailfrom);


} else {


LOG.I (TAG, "No email address specified");


Return


}


Set recipient Address


if (mailTo!= null) {


Message.setrecipient (Message.RecipientType.TO, New InternetAddress (MailTo));


LOG.I (TAG, "Recipient email Address:" + mailTo);


} else {


LOG.I (TAG, "No recipient email address specified");


Return


}


Set CC Address


if (emailccto!= null) {


Message.setrecipient (Message.RecipientType.CC, New InternetAddress (Emailccto));


LOG.I (TAG, "CC email Address:" + emailccto);


} else {


LOG.I (TAG, "No cc email address specified");


Return


}


Set the secret send address


if (emailbccto!= null) {


Message.setrecipient (Message.RecipientType.BCC, New InternetAddress (Emailbccto));


LOG.I (TAG, "Secret Send mail address:" + emailbccto);


} else {


LOG.I (TAG, "Do not specify the secret send mail Address");


Return


}


Set Message subject


Message.setsubject (subject);


LOG.I (TAG, "Mail Subject:" + subject);


Set Reply Address


Message.setreplyto (New Internetaddress[]{new internetaddress (Mailfrom)});


Create and set the first part


MimeBodyPart bodypart = new MimeBodyPart ();


if (msgcontent!= null) {


LOG.I (TAG, "Mail content:" + msgcontent);


Bodypart.setcontent (Msgcontent, Messagecontenttype);


} else {


Bodypart.setcontent ("", messagecontenttype);


}


Multipart.addbodypart (BodyPart);


Attachment file to Message


if (attachedfilelist!= null) {


For (Enumeration filelist = Attachedfilelist.elements (); filelist.hasmoreelements ();) {


FileName = (String) filelist.nextelement ();


MimeBodyPart Mbodypart = new MimeBodyPart ();





Filedatasource FDS = new Filedatasource (Messagebasepath + fileName);


LOG.I (TAG, "email sent the attachment is:" + Messagebasepath + fileName);


Mbodypart.setdatahandler (New DataHandler (FDS));


Mbodypart.setfilename (FileName);


Multipart.addbodypart (Mbodypart);


}


}


LOG.I (TAG, "Set the Mail section");


Message.setcontent (multipart);


Message.setsentdate (New Date ());


}





/**


* Send Mail method


*


* @return True to send success, False indicates unsuccessful


*/


public Boolean sendemail () {


int loopcount;


Properties Properties = System.getproperties ();


Properties.setproperty ("Mail.smtp.host", SMTPHost);


Properties.setproperty ("Mail.smtp.auth", "true");


Properties.put ("Mail.smtp.port", "25");


Mailauthenticator authenticator = new Mailauthenticator ();


Session session = Session.getinstance (properties, authenticator);


Session.setdebug (Debug);


MimeMessage mimemessage = new MimeMessage (session);





If you use transport here, there will be an error.


Smtptransport transport = New Smtptransport (Session, New URLName ("SMTP", "smtp.qq.com",, NULL, Mailauthenticator.tencent_email_user, mailauthenticator.tencent_email_pwd));


try {


Writeemail (session, MimeMessage);


Transport = Session.gettransport ("SMTP");


try {


LOG.I (TAG, "Start connecting server");


Transport.connect (SMTPHost, Mailauthenticator.tencent_email_user, mailauthenticator.tencent_email_pwd);


catch (Authenticationfailedexception e) {


E.printstacktrace ();


LOG.I (TAG, "Connection Server failed");


return false;


catch (Messagingexception e) {


E.printstacktrace ();


LOG.I (TAG, "There is an error during the sending of the message");


return false;


}


LOG.I (TAG, "Start sending mail");


Transport.sendmessage (MimeMessage, mimemessage.getallrecipients ());


Transport.close ();


LOG.I (TAG, "close connection");


catch (Messagingexception e) {


E.printstacktrace ();


LOG.I (TAG, "Send Mail Failed");


return false;


finally {


try {


if (transport!= null && transport.isconnected ()) {


Transport.close ();


LOG.I (TAG, "Close the connection in finally)";


}


catch (Messagingexception e) {


E.printstacktrace ();


}


}


LOG.I (TAG, "Mail sent successfully");


return true;


}


}





Tips---The Myauthenticator class inherits from authenticator, overriding this method





@Override


Protected Passwordauthentication getpasswordauthentication () {


return new Passwordauthentication (mailbox username, password);


}











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.