Java Code send mail sample and explanation

Source: Internet
Author: User

Download and upload attachments, send text messages and send e-mails, are very commonly used in the program functions, before recording the upload and download files and send text messages, due to the recent busy, the function of the mail sent no time to get, fortunately last night to pass the code successfully sent to 163 mailbox mail to QQ mailbox, the following is the relevant code, For specific explanations, refer to the comments in the code:
Package Test;import Java.util.arraylist;import java.util.date;import java.util.list;import java.util.Properties; Import Java.util.regex.matcher;import Java.util.regex.pattern;import Javax.mail.address;import Javax.mail.authenticator;import Javax.mail.bodypart;import Javax.mail.message;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;import com.sun.mail.util.mailsslsocketfactory;///**//*//* @author zengyuan//* @date Jan, 2016-9:55:48 am//* @Descripti        On mail Send test class//*/public class Sendmailtest {public static void main (string[] args) throws Exception {//configuration information        Properties Pro = new properties ();        Pro.put ("Mail.smtp.host", "smtp.163.com");        Pro.put ("Mail.smtp.auth", "true");        SSL encryption mailsslsocketfactory SF = NULL; SF = new MailSslsocketfactory ();        Set to trust all hosts sf.settrustallhosts (true);        Pro.put ("Mail.smtp.ssl.enable", "true");        Pro.put ("Mail.smtp.ssl.socketFactory", SF); According to the message's session properties to construct a send message session, it is important to note that the user name there is no suffix, otherwise it is not the user name//also need to note that the password here is not the normal use of the mailbox login password, but the client generated another special authorization code MAI        Lauthenticator authenticator = new Mailauthenticator ("tuzongxun123", "Client Authorization Code");        Session session = Session.getinstance (pro, authenticator);        Message message = new MimeMessage (session) based on session construction        Create email sender address from = new InternetAddress ("[email protected]");        Set the sender Message.setfrom (from) of the mail message;        Verify recipient email address list<string> toaddresslist = new arraylist<> ();        Toaddresslist.add ("[email protected]");        StringBuffer buffer = new StringBuffer (); if (!toaddresslist.isempty ()) {String regEx = "^ ([a-z0-9a-z]+[-|\\.]?) +[a-z0-9a-z]@ ([a-z0-9a-z]+ (-[a-z0-9a-z]+)?\\.)            +[a-za-z]{2,}$ ";            Pattern p = pattern.compile (regEx);                for (int i = 0; i < toaddresslist.size (); i++) {Matcher match = P.matcher (Toaddresslist.get (i));                    if (Match.matches ()) {Buffer.append (Toaddresslist.get (i));                    if (I < toaddresslist.size ()-1) {Buffer.append (",");        }}}} String toaddress = Buffer.tostring ();            if (!toaddress.isempty ()) {//Create message recipient address address[] to = Internetaddress.parse (toaddress);            Set Mail Recipient address message.setrecipients (Message.RecipientType.TO, to);            Mail Subject//message.setsubject ("Java Mail Test");            Message.setsubject ("why Wrong");            Mail container Mimemultipart Mimemultipart = new Mimemultipart ();            Set HTML BodyPart bodypart = new MimeBodyPart (); Message content//String HTMLText = "Java Mail test 111";            String HTMLText = "why Wrong";            Bodypart.setcontent (HTMLText, "text/html;charset=utf-8");          Mimemultipart.addbodypart (BodyPart);            Add Attachment list<string> fileaddresslist = new arraylist<string> ();            Fileaddresslist. Add ("c:\\users\\tuzongxun123\\desktop\\ new Microsoft Office Word document. docx");                if (fileaddresslist! = null) {BodyPart attchpart = null;                        for (int i = 0; i < fileaddresslist.size (); i++) {if (!fileaddresslist.get (i). IsEmpty ()) {                        Attchpart = new MimeBodyPart (); Accessory data source DataSource Source = new Filedatasource (fileaddresslist.get                        (i));                        Add an attachment data source to the message body Attchpart.setdatahandler (new DataHandler); Set the attachment name to the original file name AttchpaRt.setfilename (Mimeutility.encodetext (source. GetName ()));                    Mimemultipart.addbodypart (Attchpart);            }}} message.setcontent (Mimemultipart);            Message.setsentdate (New Date ());            Save Message Message.savechanges ();        Send mail transport.send (message);    }}}class Mailauthenticator extends Authenticator {/** * username */private String username;    /** * Password * */private String password;     /** * Create a new instance of Mailauthenticator.        * * @param username * @param password */public Mailauthenticator (string Username, string password) {        This.username = Username;    This.password = password;    } public String GetPassword () {return password; } @Override protected Passwordauthentication getpasswordauthentication () {return new passwordauthentication ( Username, password);    } public String GetUserName () {return username;    } public void SetPassword (String password) {this.password = password;    } public void Setusername (String username) {this.username = username; }}


Java Code send mail sample and explanation

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.