Introduction to the Java Mail delivery function implementation
1, Java Mail Introduction:
Java Mail is the use of existing mail accounts to send mail tools, for example, I registered an email account in NetEase, through the control of Java mail, I can not personally login NetEase mailbox, let the program automatically use NetEase mailbox to send mail. This mechanism is widely used in such aspects as registration activation and the sending of spam messages.
2. Configure the JavaMail development environment
Mail.jar : is the core development package that must be used to develop the JavaMail program.
Some core classes of Mail.jar files include: Session, Message, Address, Authenticator, Transport, Store, There are also some common subclasses in folder and Javax.mail.internet packages.
A:session Class (mail session)
The job of sending and receiving mail is based on this session.
The session object uses the Java.util.Properties object to obtain the mail server, user name, password information, and the entire application to use to share information.
Properties Props = new properties ();
Session session = Session.getdefaultinstance (props, null);
Or
Properties Props = new properties ();
Session session = Session.getinstance (props, null);
From the two examples above, it is not difficult to find that the second parameter is NULL, because in the above example there is no use of mail authorization (see D)
B:message class
Once the session object is established, the message body message abstract class that is sent can be constructed.
Using the Javax.mail.internet.MimeMessage subclass, this class is the mailbox information that uses the MIME type, MIME information header.
Information headers can only use US-ASCII characters
Message message = new MimeMessage (session);
Message.setcontent ("Hello", "Text/plain");//non-textual information content
Message.settext ("Hello");//plain Text information content
Message.setsubject ("First");//Set Message subject
Message.setsentdate (date);//set Mail send date
C:address
After setting up the session and message object, use the address abstract class
Use the Javax.mail.internet.InternetAddress subclass. String through the Incoming mail address
Address address = new InternetAddress ("[email protected]"); e-mail address
Address address = new InternetAddress ("[email protected]", "Technology excellence"); e-mail address with Name
Message.setfrom (address);//Set Sender
Message.setreplyto (address);//Ibid.
Message.addfrom (address[] Address);//Add multiple Senders
Message.addrecipient (type, address)//Set up the recipient
message.recipienttype.to//the addressee.
message.recipienttype.cc//cc Person
message.recipienttype.bcc//Dark Send People
D Authenticator authorized by Class
The authenticator abstract class must implement the Getpasswordauthentication () method, which is used to store the user name and password to use for authentication.
and to register in the session, the session will know which class to use for authentication.
Properties Props = new properties ();
Authenticator auth = new Myauthenticator ();
Session session = Session.getdefaultinstance (props, auth);
/**
* Custom Authorization Class
*/
public class Emailautherticator extends Authenticator {
Private String username;
private String password;
Public Emailautherticator () {
Super ();
}
Public Emailautherticator (string user, string pwd) {
Super ();
Username = user;
Password = pwd;
}
Public Passwordauthentication getpasswordauthentication () {
return new passwordauthentication (username, password);
}
}
E. Transport
Use transport abstract class when sending information (SMTP is implemented)
Transport.send (MimeMessage message);
or general usage
Of course, the methods are diverse. We can also get the transport instance corresponding to the corresponding protocol by the session. And by passing the user name, password, mail server hostname and other parameters to establish a connection with the mail server, and use the SendMessage () method to send information, and finally close the connection:
Session.setdebug (TRUE);//monitor the message sending process
Message.savechanges (); Save File
Transport Transport = Session.gettransport ("SMTP");//Get the Transport class that implements the SMTP protocol
Transport.connect (host, username, password);//Connect server
Transport.sendmessage (Message, message.getallrecipients ());//Send mail to all recipients
Transport.close ();//close connection
F. Store (server where mail is stored) and folder (directory object)
Store store = Session.getstore ("POP3");
Store.connect (host, username, password);
Folder folder = Store.getfolder ("INBOX");//pop3 protocol only one folder named INBOX is valid
Folder.open (folder.read_only);//read-only mode open
Message message[] = Folder.getmessages ();//Get Mail
System.out.println (((mimemessage) message). GetContent ());//message content (not including headers)
System.out.println (((mimemessage) message). WriteTo ());//message contents (including headers)
Folder.close (TRUE);//If you delete the message, update the folder, close
Store.close ();//Close
Java the process of sending mail:
Package Mail;import Java.io.unsupportedencodingexception;import Java.util.date;import java.util.Properties;import Javax.activation.datahandler;import Javax.activation.filedatasource;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;import Javax.mail.internet.mimeutility;public class SendMail {private static SendMail instance = Null;private SendMail () {} public static SendMail getinstance () {if (instance = = null) {instance = new SendMail ();} return instance;} public void Send (String to[], string cs[], string ms[], string subject,string content, String formemail, String filelist[] {try {Properties p = new properties ();//Properties P =//system.getproperties ();p. put ("Mail.smtp.auth", "true");p. Put ( "Mail.transPort.protocol "," SMTP ");p. Put (" Mail.smtp.host "," smtp.qq.com ");p. Put (" Mail.smtp.port "," 25 ");//Establish Session sessions = Session.getinstance (P); Message msg = new MimeMessage (session); Establish information bodypart Messagebodypart = new MimeBodyPart (); Multipart Multipart = new Mimemultipart (); Msg.setfrom (new InternetAddress (Formemail)); Sender string toList = null; String Tolistcs = null; String Tolistms = null;//sent, if (to! = null) {toList = Getmaillist (to); internetaddress[] iatolist = new internetaddress (). Parse (toList); Msg.setrecipients (Message.RecipientType.TO, iatolist); Recipient}//CC if (cs! = null) {Tolistcs = Getmaillist (CS); internetaddress[] Iatolistcs = new InternetAddress (). Parse (TOLISTC s); Msg.setrecipients (Message.RecipientType.CC, Iatolistcs); CC person}//Secret send if (ms! = NULL) {Tolistms = Getmaillist (ms); internetaddress[] Iatolistms = new InternetAddress (). Parse (tolistm s); Msg.setrecipients (Message.RecipientType.BCC, IATOLISTMS); Bcc}msg.setsentdate (New Date ()); Send date msg.setsubject (subject); ThemeMsg.settext (content); Content//Display in HTML-formatted text content messagebodypart.setcontent (content, "TEXT/HTML;CHARSET=GBK"); Multipart.addbodypart ( Messagebodypart)///2. Save multiple attachments if (fileList! = null) {Addtach (fileList, multipart);} Msg.setcontent (multipart);//mail server Authentication Transport tran = Session.gettransport ("SMTP"); Tran.connect ("Smtp.qq.com", " 1111@2qq.con "," 1q2w3e4r5dtmmm "); Tran.sendmessage (msg, msg.getallrecipients ()); Send System.out.println ("Mail sent successfully");} catch (Exception e) {e.printstacktrace ();}} Add multiple attachments public void Addtach (String filelist[], Multipart Multipart) throws Messagingexception, unsupportedencodingexception {for (int index = 0; index < filelist.length; index++) {MimeBodyPart Mailarchieve = new Mi Mebodypart (); Filedatasource FDS = new Filedatasource (Filelist[index]); Mailarchieve.setdatahandler (new DataHandler (FDS)); Mailarchieve.setfilename (Mimeutility.encodetext (Fds.getname (), "GBK", "B")); Multipart.addbodypart (MailArchieve);}} Private String getmaillist (string[] mailarray) {StringBuffer toList = nEW stringbuffer (); int length = Mailarray.length;if (Mailarray! = null && length < 2) {Tolist.append (mailarray[0 ]);} else {for (int i = 0; i < length; i++) {tolist.append (Mailarray[i]), if (I! = (length-1)) {tolist.append (",")}}} return tolist.tostring ();} public static void Main (String args[]) {SendMail send = Sendmail.getinstance (); String to[] = {"aaaa@aaaa.cn"}; String cs[] = {"laaaa@aaa.cn"}; String ms[] = null; String subject = "Test a bit"; String content = "This is the contents of the message, just the test, no reply required"; String formemail = "aaaa@mftcc.cn"; string[] arrarchievlist = new String[4];arrarchievlist[0] = "C:\\2012052914033429140297.rar"; arrArchievList[1] = "c:\\ Topsearch.html "; arrarchievlist[2] =" c:\\topsearch2.html "; arrarchievlist[3] =" c:\\logo_white.png ";//2. Save multiple attachments send.send (to, CS, MS, subject, content, Formemail, arrarchievlist);}}
JavaMail Function Introduction