Spring implementation of Java mail delivery

Source: Internet
Author: User
Tags html form set set mailmessage

because the project needs to be sent by mail, I recently learned to use the spring mechanism to send mail. Here is a general record of its implementation.

first, you need to import two packages in the project, one is Mailapi-xx.jar, and the other is Smtp-xx.jar. where xx represents the version number. If it's easier to use MAVEN, add it directly:

<dependency>    <groupId>com.sun.mail</groupId>    <artifactid>javax.mail</ Artifactid>    <version>1.5.4</version></dependency>
And then there's the way our mail is sent. If you want to make this into a tool class, you can completely change it to a static method.

private static emaildetails emaildetails;    public static void Resetemaildetails () {        emaildetails = null;        Logger.info ("Emailservice: Reset Emaildetails=null");    }
 public void SendMail (string toemail, String subject, String htmlcontent) {if (emaildetails = = null) {                Emaildetails = Isysconfigservice.getemaildetails ();            Logger.info ("Emailservice: Reset emaildetails={}", Jsonarray.fromobject (emaildetails)); } if (Stringutil.isempty (toemail) | | Stringutil.isempty (subject) | |            Stringutil.isempty (htmlcontent)) {throw new Businessexception ("The information to be sent (target mailbox, subject, content) is incomplete");            } Javamailsenderimpl Senderimpl = new Javamailsenderimpl ();            Mail server Senderimpl.sethost (Emaildetails.gethost ()) sending the mailbox;            Establish mail message, send Simple mail and HTML message difference mimemessage MailMessage = Senderimpl.createmimemessage ();           To prevent garbled characters, add the encoding set set Mimemessagehelper Messagehelper = new Mimemessagehelper (MailMessage, "UTF-8");            System.out.println ("Sender Address 1:" +systemconfig.getguestusername ()); try {//Receive Party mailbox Messagehelper. Setto (Toemail); } catch (Messagingexception e) {throw new RuntimeException ("Error in recipient mailbox address!            ");            } try {//Sender Mailbox Messagehelper.setfrom (Emaildetails.getfrom ()); } catch (Messagingexception e) {throw new RuntimeException ("error from the sender's mailbox address!            ");            } try {Messagehelper.setsubject (subject); } catch (Messagingexception e) {throw new RuntimeException ("error message subject!)            ");            The try {//TRUE indicates that the HTML-formatted message Messagehelper.settext (Htmlcontent, True) is started; } catch (Messagingexception e) {throw new RuntimeException ("Error in message content!            ");            } Properties Prop = new properties ();            Set this parameter to True to allow the server to authenticate, authenticate the user name and password correctly prop.put ("Mail.smtp.auth", "true");            Timeout time prop.put ("Mail.smtp.timeout", "25000"); Add Validation//MyauthenTicator auth = new Myauthenticator (Systemconfig.getemailusername (),//Systemconfig.getemailpassword ()); Myauthenticator auth = new Myauthenticator (Emaildetails.getusername (), EMAILDETAILS.GETPASSW            Ord ());            Session session = Session.getdefaultinstance (prop, auth);            Senderimpl.setsession (session);            Senderimpl.setjavamailproperties (prop);                Send mail try {senderimpl.send (mailmessage);            Logger.info ("Send Mail succeeded, recipient: {}, Subject: {}", toemail,subject); } catch (Exception e) {throw new Businessexception ("Failed to send mail!            "); }        }
Here we also need a validation of the class, to verify that you provide the sender's information is correct (in fact, 163 get QQ and other servers to verify the information you provide, verify that they do not send you through the others. This class can be placed in a parallel position of the method above as an inner class for a mail-sending tool class.

Verify the sender's user name and password, after verification succeeds, the mailbox server is allowed to send mail    class Myauthenticator extends authenticator{        private String username;        private String password;        Public myauthenticator (String username,string password) {            super ();            This.username=username;            This.password=password;        }        Protected Passwordauthentication getpasswordauthentication () {            return new Passwordauthentication (username, password);        }    }
Of course, with these mass of the natural become a very simple thing (overload can):

Mass    public  void SendMail (list<string> toemaillist, String subject, String htmlcontent) {for        ( String toemail:toemaillist) {            sendMail (toemail,subject,htmlcontent);        }     }
This will enable the delivery of the message.

Here are the parameters: Sender parameters: From: Sender mailbox, Host: Sending server (if your sender is 163 mailbox, this is smtp.163.com); Username: The user name of the sender's mailbox; Password: Sender's mailbox password. I am here because it is stored in JSON form in the database, so using a class to manage is Emaildetails, can be configured by itself.

Send data: toemail: Inbox, Subject: Theme, content in htmlcontent:html form.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring implementation of Java mail delivery

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.