How to Use the JavaMail program in android development, androidjavamail

Source: Internet
Author: User
Tags mailmessage microsoft outlook

How to Use the JavaMail program in android development, androidjavamail

JavaMail is a programming interface for developers to process emails. It is an API released by Sun to process emails. It can easily perform some common mail Transmission. We can develop applications similar to Microsoft outlook based on JavaMail. JavaMail is an optional package, so if you need to use it, you must first download it from the java official website.

This article mainly introduces JavaMail. javamail does not need a third-party email program to send emails. For future convenience, I wrote some code

Steps for configuring Javamail-Android:

Download the JavaMail package for Android, including additional. jar, mail. jar, activation. jar, and JavaMail-Android.

At the same directory level as src in the project, create a folder lib and put the three downloaded jar packages into this folder.

Right-click Properties> Java Build Path> Libraries, select Add External JARs, and find the Three jar packages in the lib directory of the project.

My code has three classes:

First Class: MailSenderInfo. java

Package com. util. mail;/*** basic information required for sending an email */import java. util. properties; public class MailSenderInfo {// IP address and port of the server sending mail private String mailServerHost; private String mailServerPort = "25"; // private String fromAddress; // The email recipient's address: private String toAddress; // the userName and password used to log on to the email sending server: private String userName; private String password; // whether authentication is required: private boolean validate = false; // Email Subject private S Tring subject; // private String content of the mail text; // File Name of the Mail Attachment private String [] attachFileNames;/*** get mail session attribute */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

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 information of the mail to be sent */ public boolean sendTextMail (MultiMailSenderInfo mailInfo) {// determine whether identity authentication is required. MyAuthenticator authenticator = null; Properties pro = mailInfo. getProperties (); if (mailInfo. isValidate () {// If identity authentication is required, create a authenticator = new MyAuthenticator (mailInfo. getUserName (), MailInfo. getPassword ();} // construct a mail sending session Session sendMailSession = Session based on the mail session attribute and password validators. getDefaultInstance (pro, authenticator); try {// create an email Message mailMessage = new MimeMessage (sendMailSession) based on the session; // create the mail sender Address from = new InternetAddress (mailInfo. getFromAddress (); // sets the sender of the email message mailMessage. setFrom (from); // create the email receiver Address and set it to Address [] tos = null; String [] receive Rs = mailInfo. getReceivers (); if (receivers! = Null) {// create an address 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. the TO attribute indicates that the receiver type is TO mailMessage. setRecipients (Message. recipientTy Pe. TO, tos); // set the subject of the email message mailMessage. setSubject (mailInfo. getSubject (); // set the mail message sending time mailMessage. setSentDate (new Date (); // you can specify String mailContent = mailInfo. getContent (); mailMessage. setText (mailContent); // send the email Transport. send (mailMessage); return true;} catch (MessagingException ex) {ex. printStackTrace ();} return false;}/*** send an email to multiple recipients with the Html content * @ param mailInfo containing the email sending information * @ retu Rn */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 the mail sender address Address from = new InternetAddress (mailInfo. getFromAddress (); mailMessage. setFrom (from); // create the email receiver Address and set it to Address [] tos = null; String [] receivers = mailInfo. getReceivers (); if (receivers! = Null) {// create an address 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 mailMessage attribute. setRecipients (Message. recipientType. TO, tos); mail Message. setSubject (mailInfo. getSubject (); mailMessage. setSentDate (new Date (); // set the mail content Multipart mainPart = new MimeMultipart (); BodyPart html = new MimeBodyPart (); html. setContent (mailInfo. getContent (), "text/html; charset = GBK"); mainPart. addBodyPart (html); mailMessage. setContent (mainPart); // send the email Transport. send (mailMessage); return true;} catch (MessagingException ex) {ex. printStackTrace () ;} Return false;}/*** send a CC-containing email * @ param mailInfo the message to be sent * @ 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 {Messa Ge mailMessage = new MimeMessage (sendMailSession); // create the mail sender Address from = new InternetAddress (mailInfo. getFromAddress (); mailMessage. setFrom (from); // create the recipient Address of the email and set it to Address to = new InternetAddress (mailInfo. getToAddress (); mailMessage. setRecipient (Message. recipientType. TO, to); // obtain the CC information String [] ccs = mailInfo. getCcs (); if (ccs! = Null) {// create an 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 Mail Information. Note that the type is Message. recipientType. CC mailMessage. setRecipients (Message. recipientType. CC, ccAdresses);} mailMessage. setSubject (mailInfo. getSubject (); mailMessage. setSentDate (new Date (); // set the mail content Multipart mainPart = new MimeMultipart (); BodyPart html = new MimeBodyPart (); html. setContent (mailInfo. getContent (), "text/html; charset = GBK"); mainPart. addBodyPart (html); mailMessage. setContent (mainPart); // send the email Transport. send (mailMessage); return true;} catch (MessagingException ex) {ex. printStackTrace ();} return false;}/*** send basic information of Multi-recipient mail */public static class MultiMailSenderInfo extends MailSenderInfo {// recipient of the mail, you can have multiple private String [] receivers; // email CC recipients. You can have multiple 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 ;}}}

Third class: 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);    }}

The following code uses the above three classes:

Public static void main (String [] args) {// This class mainly sets the mail 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 email title"); mailInfo. setContent ("set email content"); String [] receivers = new String [] {"*** @ 163.com"," *** @ tom.com "}; string [] ccs = receivers; mailInfo. setReceivers (receivers); mailInfo. setCcs (ccs); // This class is mainly used to send mail MultiMailsender sms = new MultiMailsender (); sms. sendTextMail (mailInfo); // transmission style format MultiMailsender. sendHtmlMail (mailInfo); // sends the html format MultiMailsender. sendMailtoMultiCC (mailInfo); // send a CC

Finally, I will give my friends some notes:

1. Using this code, you can complete the javamail mail sending function and send multiple mailboxes. Three categories are indispensable.

2. I package the com. util. mail package for these three classes. If you do not like the package, you can change it by yourself, but the three class files must be in the same package.

3. Do not use the email address you just registered to send emails in the program. If your 163 email address is just registered, do not use "smtp.163.com ". Because you cannot send it out. The newly registered email address does not give you such permissions, that is, you cannot pass verification. It takes a long time to use your frequently used email address.

4. Another problem is mailInfo. setMailServerHost ("smtp.163.com"); and mailInfo. setFromAddress ("xxx@163.com. That is, if you use the 163smtp server, you must use the 163 email address to send the email. If you do not use the email address, the email will not be sent successfully.

5. There are many online explanations about javamail verification errors, but I only see one. Is my third class. As long as you copy all the code, I think there will be no problem.

6. Then, add the network access permission to the Android project.

This article mainly introduces the configuration steps of Javamail-Android and the code of the three classes. At last, we provide six suggestions. I hope we will pay attention to some issues when using the JavaMail program in android development.

 

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.