Java Study Notes (1) -- send emails in Java

Source: Internet
Author: User
Tags mailmessage

I saw the email development video explained by Zhang Xiaoxiang, but I only watched a small part of it. At that time, I was a little newbie and didn't understand it. I thought it was a very complicated technology. The mail sending function is used in a small project that has recently been practiced. This function is implemented by referring to the Code on the Internet. Now, it's so easy!


Before enabling this function, you need to download the jar package mail. Jar required for sending emails. You can also download it here.


Create a Java class file myauthenticator. java. The Code is as follows:


packagecom.ldfsoft.common; importjavax.mail.Authenticator;importjavax.mail.PasswordAuthentication;   public classMyAuthenticator 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);              }}

These files inherit the authenticator class in the mail. jar package.


Then create a new DTO file mailsenderdto. java. The Code is as follows:


Package COM. ldfsoft. dto; import Java. util. properties; publicclass mailsenderdto {// IP address and port of the server on which the email is sent private stringmailserverhost; private stringmailserverport = "25"; // address of the mail sender private stringfromaddress; // The email recipient's address: Private stringtoaddress; // the username and password used to log on to the email sending server: Private stringusername; private stringpassword; // whether authentication is required: privateboolean validate = false; // mail subject private stringsubject; // mail text content priv Ate stringcontent; // the file name of the email attachment: Private string [] attachfilenames;/*** get the mail session attribute */Public propertiesgetproperties () {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 () {returnmailserverhost;} publicvoid setmailserverhost (string mailserverhost) {This. mailserverhost = mailserverhost;} publicstringgetmailserverport () {returnmailserverport;} publicvoid setmailserverport (string mailserverport) {This. mailserverport = mailserverport;} publicboolean isvalidate () {returnvalidate;} publicvoid setvalidate (Boolean validate) {This. validate = validate;} Public String [] getattachfilenames () {returnattachfilenames;} publicvoid setattachfilenames (string [] filenames) {This. attachfilenames = filenames;} Public String getfromaddress () {returnfromaddress;} publicvoid setfromaddress (string fromaddress) {This. fromaddress = fromaddress;} Public String GetPassword () {returnpassword;} publicvoid setpassword (string password) {This. password = password;} Public String gettoaddress () {returntoaddress;} publicvoid settoaddress (string toaddress) {This. toaddress = toaddress;} Public String GetUserName () {returnusername;} publicvoid setusername (string username) {This. username = username;} Public String getsubject () {returnsubject;} publicvoid setsubject (string subject) {This. subject = subject;} Public String getcontent () {returncontent;} publicvoid setcontent (string textcontent) {This. content = textcontent ;}}

Create a new Java file mailsender. Java, which contains two methods: one for sending emails in text format and the other for sending emails in HTML format. The Code is as follows:


Package COM. ldfsoft. common; 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; import COM. ldfsoft. dto. mailsenderdto; publicclass mailsender {/*** send mail in text format * @ Param mailinfo information of the mail to be sent */publicbooleansendtextmail (mailsenderdto mailinfo) {// determine whether identity authentication is required. myauthenticatorauthenticator = NULL; properties pro = mailinfo. getproperties (); If (mailinfo. isvalidate () {// If identity authentication is required, create a authenticator = newmyauthenticator (mailinfo. getUserName (), mailinfo. getPassword ();} // construct a session sessionsendmailsession = session to send an email 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 = newinternetaddress (mailinfo. getfromaddress (); // sets the sender of the email message mailmessage. setfrom (from); // create the email receiver address and set it to address to = newinternetaddress (mailinfo. gettoaddress (); mailmessage. setrecipient (message. recipienttype. to, to); // 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); returntrue;} catch (messagingexception ex) {ex. printstacktrace ();} returnfalse;}/*** send an email in HTML format * @ Param mailinfo message to be sent */Public Boolean sendhtmlmail (mailsenderdto mailinfo) {// determine whether identity authentication is required. myauthenticatorauthenticator = NULL; properties pro = mailinfo. getproperties (); // If identity authentication is required, create a password validator if (mailinfo. isvalidate () {authenticator = newmyauthenticator (mailinfo. getUserName (), mailinfo. getPassword ();} // construct a session sessionsendmailsession = session to send an email 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 = newinternetaddress (mailinfo. getfromaddress (); // sets the sender of the email message mailmessage. setfrom (from); // create the email receiver address and set it to address to = newinternetaddress (mailinfo. gettoaddress (); // message. recipienttype. the to attribute indicates that the receiver type is to mailmessage. setrecipient (message. recipienttype. to, to); // set the subject of the email message mailmessage. setsubject (mailinfo. getsubject (); // set the mail message sending time mailmessage. setsentdate (new date (); // The minimultipart class is a container class that contains the multipart mainpart = new mimemultipart (); // create a mimebodypart bodypart HTML containing HTML content = newmimebodypart (); // set the HTML content in HTML. setcontent (mailinfo. getcontent (), "text/html; charset = UTF-8"); mainpart. addbodypart (HTML); // set the minimultipart object to mailmessage. setcontent (mainpart); // send the email transport. send (mailmessage); returntrue;} catch (messagingexception ex) {ex. printstacktrace ();} returnfalse ;}}

Create a tool class javautil. Java to encapsulate the method for sending emails. The Code is as follows:


Packagecom. ldfsoft. util; import COM. ldfsoft. common. mailsender; importcom. ldfsoft. dto. mailsenderdto; Public classjavautil {/*** send email */Public void sendemail (string email) {try {string mailtitle = "[my online storage] Account Activation email "; string mailcontent = "<br> Dear [my online storage] user: <br>" + "Hello! Thank you for registering your [my online storage] account. click the following link to complete registration: <br> "+" <ahref = \ "http: // localhost: 9080/mydisk/SWF/activateemail.html # email = "+ email +" \ "> http: // localhost: 9080/mydisk/SWF/activateemail.html # email = "+ email +" </a> <br> "+" (if the link cannot be clicked, copy and paste it to the address bar of your browser.) <br> "+" Your Email: "+ email +" <br> "+" email can be used as your account to log on to [my online storage ]. <Br> "+" This email is automatically sent by the system. Please do not reply directly! Thank you for your visit and wish you a pleasant stay! <Br> "+" [my online storage] Service Center "; mailsenderdto mailinfo = newmailsenderdto (); mailinfo. setmailserverhost ("smtp.163.com"); mailinfo. setmailserverport ("25"); mailinfo. setvalidate (true); mailinfo. setusername ("lindf123of@163.com"); mailinfo. setpassword ("*******"); // your email password mailinfo. setfromaddress ("lindf123of@163.com"); // the sender's email address mailinfo. settoaddress (email); // the recipient's email address mailinfo. setsubject (mailtitle); mailinfo. se Tcontent (mailcontent); // This class mainly sends mail mailsender MS = new mailsender (); Ms. sendhtmlmail (mailinfo); // sends the HTML format} catch (exception e) {system. out. println ("failed! ");}}}

The parameter of this method is the email to be sent.


Now you can send an email. You can call this method in the main method for testing. The following is the test result:



 

Well, it is implemented. But there is another solution. We can see that some email attributes are hardcoded into the program, which is not easy to maintain. This is a problem to be solved later. I will solve this problem as soon as possible.

For some of the Code in this article, please refer to the following link: http://www.blogjava.net/wangfun/archive/2009/04/15/265748.html!


This is my learning result. You can reprint it. You are welcome to share it with me. However, you must provide the link to this article at http://blog.csdn.net/youqishini/article/details/7897751,thank you ~




 

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.