Spring uses spring to send mail

Source: Internet
Author: User

The core of Spring email abstraction is the MailSender interface, the implementation of MailSender can be connected to the email server to achieve mail delivery functions, such as:

Spring comes with a mailsender implementation is Javamailsenderimpl, it also uses the JavaMail API to send email, before use, You must first assemble the Javamailsenderimpl as a bean in the spring application context, as follows:

@Bean  Public MailSender MailSender (Environment env) {    new  Javamailsenderimpl ();    Mailsender.sethost (Env.getproperty ("Mailserver.host"));         return MailSender;}

By default, Javamailsenderimpl assumes that the mail server listens on port 25, and if the mail server listens on a different port, you can use the Port property to specify its port number, which is added in the MailSender () method above:

Mailsender.setport (Env.getproperty ("Mailserver.port"));

If the mail server requires authentication, you will also need to set username and password:

Mailsender.setusername (Env.getproperty ("Mailserver.username")); Mailsender.setpassword (Env.getProperty ( "Mailserver.password"));

This allows the Javamailsenderimpl to be configured so that it can create its own mail session, If Javax.mail.MailSession is already configured in Jndi, there is no need to configure detailed server details for Javamailsenderimpl, which can be configured to use the mailsession that is already ready in Jndi.

With Jndiobjectfactorybean, you can configure a bean in the following @bean method, which looks for mailsession from Jndi:

@Bean  Public Jndiobjectfactorybean mailsession () {    new  Jndiobjectfactorybean ();    Jndi.setjndiname ("mail/session");    Jndi.setproxyinterface (mailsession. class );    Jndi.setresourceref (true);         return Jndi;}

You can then use the spring <jee:jndi-lookup> element to get the object from Jndi, where you can use <jee:jndi-lookup> to create a bean that references a mail session in Jndi:

<id= "MailSession"  jndi-name= "Mail/session"  resource-ref  = "true">

Once the mail session is ready, you can assemble it into the mailsender bean:

@Bean  Public mailsender MailSender (mailsession mailsession) {    new  Javamailsenderimpl ();    Mailsender.setsession (mailsession);         return MailSender;}

By assembling the mail session into the Javamailsenderimpl session property, the original server configuration is completely replaced, and now the mail session is configured and managed completely through Jndi. Javamailsenderimpl can focus on sending mail without having to handle the mail server on its own.

Then we need to assemble the mailsender into our business Layer implementation class (assuming the Spitteremailserviceimpl Class), as follows:

@AutowiredJavaMailSender MailSender;

Then want to send an email message to spitter users of his friend wrote a new spittle, then need a way to send email, this method to accept the email address and spittle object information, the following method is to use the mail transmitter to complete the function:

 Public void Sendsimplespittleemail (stirng to, spittle spittle) {    new  simplemailmessage ();     = Spittle.getspitter (). Getfullname ();    Message.setfrom ("[email protected]");  // Email Address     Message.setto (to);    Message.setsubject ("New spittle from" + spittername);     + "says:" + Spittle.gettext ());    Mailsender.send (message);}

The last step in the code above passes the message to the Send () method of the mail sender, so that the message is sent out.

Send an email with an attachment

Message sent successfully, now try to send an email with an attachment, to send an attachment to create a multipart type of message, email is composed of several parts, part of which is the email body, the other part is the attachment. To send a multipart type of email, you need to create a MIME message that starts with the Createmimemessage () method of the Mail sender:

MimeMessage message = Mailsender.createmimemessage ();

However, using the Javax.mail.internet.MimeMessage API here is a bit cumbersome, and you can use the Mimemessagehelper simple operation provided by spring to instantiate it mimemessage pass it to it.

New true);  // True indicates a multipart type

Once you get the Mimemessagehelper instance, you can start assembling the email message:

String spittername = spittle.getspitter (). Getfullname (); Helper.setform ("[email protected]"); Helper.setto (To), Helper.setsubject ("New spittle from" ++ "says:" +spittle.gettext ());

Add an attachment below and take the picture as an example, as long as you pass this resource to the helper's AddAttachment method:

New Filesystemresource ("/file/test.png"); Helper.addattachment ("test.png", image);

Here the spring Filesystemresource is used to load the test.png under the Classpath, and then AddAttachment () is called, the first parameter is the name of the attachment to be added to the email, and the second parameter is a resource file.

Here multipart type of email has been built, and now it is necessary to use Mimemessagehelper to send an email with attachments, the complete code is as follows:

 Public voidSendspittleemailwithattachment (stirng to, spittle spittle)throwsmessagingexception {mimemessage message=Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (Message,true); String Spittername=Spittle.getspitter (). Getfullname (); Helper.setform ("[Email protected]");    Helper.setto (to); Helper.setsubject ("New spittle from" +spittername); Helper.settext (Spittername+ "says:" +Spittle.gettext ()); Filesystemresource Image=NewFilesystemresource ("/file/test.png"); Helper.addattachment ("Test.png", image); Mailsender.send (message);}

In this case, a successful email with an attachment is sent.

Note: More articles welcome to the public number in the view, the public number id:weknow619.

Spring uses spring to send mail

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.