How to use the JavaMail program in Android development

Source: Internet
Author: User
Tags mailmessage microsoft outlook

JavaMail is a programming interface for developers to handle e-mail. It is the API that Sun releases to handle email. It is easy to perform some common mail transfer. We can develop an application similar to Microsoft Outlook based on JavaMail. JavaMail is an optional package, so you need to download it first from the Java official website if you need to use it.

This article mainly introduces Javamail,javamail sending mail is really a troublesome problem without a third-party mail program. For later use, I wrote a piece of code

Javamail-android Configuration steps:

Download Android version JavaMail pack, Additional.jar, Mail.jar and Activation.jar,javamail-android

At the same directory level as the project and SRC, create a new folder Lib to put the downloaded 3 jar packages into the folder

Right-->properties->java Build path->libraries, select Add External JARs, find the 3 jar packages under the project Lib directory

My code has three classes:

First Class: Mailsenderinfo.java

Package com.util.mail;/** * Basic information to be used for sending mail */import java.util.Properties;     public class Mailsenderinfo {//The IP and port of the server sending the message private String mailserverhost;     Private String Mailserverport = "25";     Email Sender's address private String fromaddress;     The address of the mail recipient is private String toaddress;     Login Mail sending server username and password private String userName;     private String password;     Whether to require authentication private Boolean validate = false;     Message subject private String subject;     The text contents of the message are private String content;       Message attachment filename private string[] attachfilenames;       /** * Get mail Session Properties */Public Properties GetProperties () {Properties P = new properties ();       P.put ("Mail.smtp.host", this.mailserverhost);       P.put ("Mail.smtp.port", This.mailserverport); P.put ("Mail.smtp.auth", validate?)       "True": "false");     return p;     } public String Getmailserverhost () {return mailserverhost; } public void Setmailserverhost (String mailserverhost){this.mailserverhost = Mailserverhost;     } public String Getmailserverport () {return mailserverport;     } public void Setmailserverport (String mailserverport) {this.mailserverport = Mailserverport;     } public boolean isvalidate () {return validate;     The public void Setvalidate (Boolean validate) {this.validate = validate;     } public string[] Getattachfilenames () {return attachfilenames;     } public void Setattachfilenames (string[] fileNames) {this.attachfilenames = FileNames;     } public String getfromaddress () {return fromaddress;     } public void Setfromaddress (String fromaddress) {this.fromaddress = fromaddress;     } public String GetPassword () {return password;     } public void SetPassword (String password) {this.password = password;     } public String gettoaddress () {return toaddress; } public void Settoaddress (String toaddress) {this.toadDress = toaddress;     } public String GetUserName () {return userName;     } public void Setusername (String userName) {this.username = UserName;     } public String Getsubject () {return subject;     } public void Setsubject (String subject) {this.subject = subject;     } public String GetContent () {return content;     } public void SetContent (String textcontent) {this.content = textcontent; } }

Second class: Multimailsender.java

Package com.util.mail; Import Java.util.date;import java.util.Properties; Import Javax.mail.address;import Javax.mail.bodypart;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;       /** * Send mail to multiple recipients, CC mail */public class Multimailsender {/** * send messages in text format * @param mailinfo messages to be sent */Public Boolean sendtextmail (Multimailsenderinfo mailinfo) {//Determine if authentication is required Myauthenticato           R authenticator = null;          Properties Pro = Mailinfo.getproperties (); if (Mailinfo.isvalidate ()) {//If authentication is required, create a password validator authenticator = new Myauthenticator (mailinfo.get           UserName (), Mailinfo.getpassword ()); }//Based on message session properties and password validator constructs a session session SE that sends a messageNdmailsession = Session.getdefaultinstance (pro,authenticator);           try {//Create a mail message based on session MailMessage = new MimeMessage (sendmailsession);           Create mail Sender address from = new InternetAddress (mailinfo.getfromaddress ());           Set the sender Mailmessage.setfrom (from) of the mail message;           Create the recipient address of the message and set it to the mail message in address[] tos = NULL;          String[] Receivers = mailinfo.getreceivers ();              if (receivers! = NULL) {//creates an address for each message recipient TOS = new Internetaddress[receivers.length + 1];              Tos[0] = new InternetAddress (mailinfo.gettoaddress ());              for (int i=0; i<receivers.length; i++) {tos[i+1] = new internetaddress (receivers[i]);              }} else {tos = new internetaddress[1];          Tos[0] = new InternetAddress (mailinfo.gettoaddress ()); }//Message.RecipientType.TO property indicates the recipient's type is to MAILMESSAGE.SETREcipients (Message.recipienttype.to,tos);           Set the subject of the mail message Mailmessage.setsubject (Mailinfo.getsubject ());           Sets the time mailmessage.setsentdate the mail message is sent (new Date ());           Set the main content of the 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 to multiple recipients, with HTML content * @param mailinfo messages sent with message * @return */public static Boolean Sendmai        Ltomultireceiver (Multimailsenderinfo mailinfo) {Myauthenticator authenticator = null; if (Mailinfo.isvalidate ()) {authenticator = new Myauthenticator (Mailinfo.getusername (), Mai        Linfo.getpassword ()); } Session sendmailsession = Session.getinstance (mailinfo. GetProperties (), AuthenticatOR);            try {Message mailmessage = new MimeMessage (sendmailsession);            Create mail Sender address from = new InternetAddress (mailinfo.getfromaddress ());            Mailmessage.setfrom (from);            Create the recipient address of the message and set it to the mail message in address[] tos = NULL;            String[] Receivers = mailinfo.getreceivers ();                if (receivers! = NULL) {//creates an address for each message recipient TOS = new Internetaddress[receivers.length + 1];                Tos[0] = new InternetAddress (mailinfo.gettoaddress ());                for (int i=0; i<receivers.length; i++) {tos[i+1] = new internetaddress (receivers[i]);                }} else {tos = new internetaddress[1];            Tos[0] = new InternetAddress (mailinfo.gettoaddress ());                         }//Add all recipient addresses to the Mail Recipient attribute mailmessage.setrecipients (Message.RecipientType.TO, TOS); Mailmessage.setsubject (mailinfo.getsUbject ());            Mailmessage.setsentdate (New Date ());            Set the message content Multipart Mainpart = new Mimemultipart ();            BodyPart html = new MimeBodyPart (); Html.setcontent (Mailinfo.getcontent (), "text/html;            CHARSET=GBK ");            Mainpart.addbodypart (HTML);            Mailmessage.setcontent (Mainpart);            Send mail Transport.send (mailmessage);        return true;        } catch (Messagingexception ex) {ex.printstacktrace ();    } return false; /** * Send CC messages * @param mailinfo messages to be sent * @return */public static Boolean Sendmailtomul        TICC (Multimailsenderinfo mailinfo) {Myauthenticator authenticator = null; if (Mailinfo.isvalidate ()) {authenticator = new Myauthenticator (Mailinfo.getusername (), Mai        Linfo.getpassword ()); } Session sendmailsession = Session.getinstance (mailinfo. GetProperties (), AuthenticatOR);            try {Message mailmessage = new MimeMessage (sendmailsession);            Create mail Sender address from = new InternetAddress (mailinfo.getfromaddress ());            Mailmessage.setfrom (from);            Create the recipient address of the message, and set it to the mail message in addr to = new InternetAddress (mailinfo.gettoaddress ());                         Mailmessage.setrecipient (Message.RecipientType.TO, to);            Get cc information string[] CCS = Mailinfo.getccs ();                if (CCS! = NULL) {//creates an address for each message recipient address[] ccadresses = new Internetaddress[ccs.length];                for (int i=0; i<ccs.length; i++) {ccadresses[i] = new internetaddress (ccs[i]); }//To set the CC information to the message message, note that the type is Message.RecipientType.CC mailmessage.setrecipients (messag            e.recipienttype.cc, ccadresses);            } mailmessage.setsubject (Mailinfo.getsubject ()); Mailmessage.setsentdatE (New Date ());            Set the message content Multipart Mainpart = new Mimemultipart ();            BodyPart html = new MimeBodyPart (); Html.setcontent (Mailinfo.getcontent (), "text/html;            CHARSET=GBK ");            Mainpart.addbodypart (HTML);            Mailmessage.setcontent (Mainpart);            Send mail Transport.send (mailmessage);        return true;        } catch (Messagingexception ex) {ex.printstacktrace ();    } return false; /** * Basic information for sending multi-recipient type messages */public static class Multimailsenderinfo extends mailsenderinfo{//Mail        The recipient can have multiple private string[] receivers;                 The CC of the message can have more than one private string[] CCS;        Public string[] Getccs () {return CCS;        } public void Setccs (string[] CCS) {This.ccs = CCS;        } public string[] Getreceivers () {return receivers;         } public void Setreceivers (string[] receivers) {   This.receivers = receivers; }    }}

Class Three: Myauthenticator.java

Package com.util.mail;  Import javax.mail.*;    public class Myauthenticator extends authenticator{    String username=null;    String Password=null;           Public Myauthenticator () {    } public    Myauthenticator (string Username, string password) {         This.username = Username;         This.password = password;     }     Protected Passwordauthentication getpasswordauthentication () {        return new passwordauthentication (UserName, password);}    }

Here's the code for using the above three classes:

public static void Main (string[] args) {         //This class is primarily set up mail      multimailsenderinfo mailinfo = new Multimailsenderinfo ();       mailinfo.setmailserverhost ("smtp.163.com");       Mailinfo.setmailserverport ("+");       Mailinfo.setvalidate (true);       Mailinfo.setusername ("[email protected]");       Mailinfo.setpassword ("**********");//Your email password       mailinfo.setfromaddress ("[email protected]");       Mailinfo.settoaddress ("[email protected]");       Mailinfo.setsubject ("Set mailbox Header");       Mailinfo.setcontent ("Set mailbox Contents");      String[] Receivers = new string[]{"***@163.com", "* * * @tom. com"};       String[] CCS = receivers; Mailinfo.setreceivers (receivers);       Mailinfo.setccs (CCS);       This class is primarily to send mail       multimailsender SMS = new Multimailsender ();       Sms.sendtextmail (mailinfo);//Send stylistic format       multimailsender.sendhtmlmail (mailinfo);//Send HTML format       MULTIMAILSENDER.SENDMAILTOMULTICC (mailinfo);//Send CC

Finally, give a few points of attention to friends:

1, use this code you can complete your javamail mail sending function, send multiple mailboxes. Three classes are indispensable.

2, these three classes I pack is used Com.util.mail package, if not like, you can change yourself, but three class files must be in the same package

3, do not use the mailbox you just registered in the program to send mail, if your 163 mailbox is just registered soon, then you do not use "smtp.163.com". Because you can't send it out. The newly registered mailbox will not give you this permission, that is, you can not pass the verification. Want to use your regular mailbox, and the time is longer.

4. Another problem is mailinfo.setmailserverhost ("smtp.163.com"), and Mailinfo.setfromaddress ("[email protected]"); That is, if you use a 163SMTP server, then the e-mail address must be 163 of the mailbox, if not, it will not be sent successfully.

5, about the JavaMail verification error problem, the online explanation has many, but I saw only one. is my third class. All you have to do is copy the code and I think it won't be a problem.

6. Then add network access to your Android project

This article mainly introduces the javamail-android configuration steps and three classes of code, and finally gives six suggestions, I hope we use the JavaMail program in Android development need to pay attention to some problems.

How to use the JavaMail program in Android development

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.