Android uses JavaMail to send mail

Source: Internet
Author: User
Tags static class mailmessage

Javamail-android Configuration steps:

Download Android version JavaMail packs, Additional.jar, Mail.jar and Activation.jar, download address javamail-android

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

Right-click->properties->java build path->libraries, select Add External JARs, find 3 jar packages in the item's LIB directory


My code has three classes:
First Class: Mailsenderinfo.java

The code is as follows Copy Code
Package com.util.mail;


/**


* Basic information to be used for sending mail


*/


Import java.util.Properties;


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 = false;


Message subject


Private String subject;


Text content of a message


Private String content;


File name of the message attachment


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;


}


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

The code is as follows Copy Code

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 mail in text format


* @param mailinfo messages to be sent


*/


public boolean sendtextmail (Multimailsenderinfo 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[] tos = NULL;


String[] Receivers = mailinfo.getreceivers ();


if (receivers!= null) {


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


}

The Message.RecipientType.TO property indicates that the recipient's type is to


Mailmessage.setrecipients (Message.recipienttype.to,tos);


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 to multiple recipients with HTML content


* @param mailinfo with information about sending mail


* @return


*/


public static Boolean sendmailtomultireceiver (Multimailsenderinfo mailinfo) {


Myauthenticator authenticator = null;


if (Mailinfo.isvalidate ()) {


Authenticator = new Myauthenticator (Mailinfo.getusername (),


Mailinfo.getpassword ());


}


Session sendmailsession = Session.getinstance (mailinfo


. GetProperties (), authenticator);


try {


Message MailMessage = new MimeMessage (sendmailsession);


Create Mail Sender Address


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


Mailmessage.setfrom (from);


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


address[] tos = NULL;


String[] Receivers = mailinfo.getreceivers ();


if (receivers!= null) {


Create 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 message recipient properties


Mailmessage.setrecipients (Message.RecipientType.TO, TOS);





Mailmessage.setsubject (Mailinfo.getsubject ());


Mailmessage.setsentdate (New Date ());


Set up 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 Mail


* @param mailinfo message for outgoing messages


* @return


*/


public static Boolean SENDMAILTOMULTICC (Multimailsenderinfo mailinfo) {


Myauthenticator authenticator = null;


if (Mailinfo.isvalidate ()) {


Authenticator = new Myauthenticator (Mailinfo.getusername (),


Mailinfo.getpassword ());


}


Session sendmailsession = Session.getinstance (mailinfo


. GetProperties (), authenticator);


try {


Message MailMessage = new MimeMessage (sendmailsession);


Create Mail Sender Address


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


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





Get cc person Information


String[] CCS = Mailinfo.getccs ();


if (CCS!= null) {


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


}


Set the CC information to the message information, note that the type is Message.RecipientType.CC


Mailmessage.setrecipients (Message.RecipientType.CC, ccadresses);


}





Mailmessage.setsubject (Mailinfo.getsubject ());


Mailmessage.setsentdate (New Date ());


Set up 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 multiple recipient types of mail


*/


public static class Multimailsenderinfo extends mailsenderinfo{


The recipient of the message can have multiple


Private string[] receivers;


CC of a message, you can have multiple


Private string[] CCS;





Public string[] Getccs () {


return to CCS;


}


public void Setccs (string[] CCS) {


This.ccs = CCS;


}


Public string[] Getreceivers () {


return receivers;


}


public void Setreceivers (string[] receivers) {


This.receivers = receivers;


}


}


}

A third class:

The code is as follows Copy Code

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 is a code that uses the above three classes:

The code is as follows Copy Code
public static void Main (string[] args) {


This class is primarily about setting up messages


Multimailsenderinfo mailinfo = new Multimailsenderinfo ();


Mailinfo.setmailserverhost ("smtp.163.com");


Mailinfo.setmailserverport ("25");


Mailinfo.setvalidate (TRUE);


Mailinfo.setusername ("xxx@163.com");


Mailinfo.setpassword ("**********");//Your email password


Mailinfo.setfromaddress ("xxx@163.com");


Mailinfo.settoaddress ("xxx@163.com");


Mailinfo.setsubject ("Set mailbox title");


Mailinfo.setcontent ("Set mailbox Content");


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 friends a few attention to places:
1, the use of this code you can complete your JavaMail mail delivery 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, but three class files must be in the same package
3, do not use the mailbox you have just registered in the program to send e-mail, if your 163 mailbox is just registered soon, then you do not use the "smtp.163.com". Because you can't send out. Just registered mailbox will not give you this permission, that is, you can not pass the verification. Use the mailbox you use frequently, and the time is long.
4. Another problem is mailinfo.setmailserverhost ("smtp.163.com") and Mailinfo.setfromaddress ("xxx@163.com"); That is, if you use a 163SMTP server, the e-mail address must be sent to 163 of the mailbox, if not, it will not be sent successfully.
5, on the issue of JavaMail validation errors, there are many explanations on the web, but I see only one. That's my third class. All you have to do is copy the code, and I don't think it's going to be a problem.

6, and then add Network access rights to the Android project

  code is as follows copy code

< Uses-permission android:name= "Android.permission.INTERNET" ></USES-PERMISSION>

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.