Recommended View Original Blog reprint from: Configure Spring Send mail
The core of Spring email abstraction is the MailSender interface. As the name implies, the implementation of MailSender can be connected to the email server to achieve the function of mail delivery.
Spring comes with a mailsender implementation of the--javamailsenderimpl. It uses the JavaMail API to send email.
Configuring the Mail Sender
Required Core maven:
<Dependency><Groupid>org.springframework</Groupid><Artifactid>spring-context-support</artifactid> < version>4.3.8.release</version > </dependency> <dependency> <groupid>javax.mail</groupid> < Artifactid>mail</artifactid> <version>1.4.7</version> Span class= "Hljs-tag" ></DEPENDENCY>
To configure the Bean:
Publicclass rootconfig {/** * Config Mail transmitter * @return */ @Bean public mailsender mailsender () {Javamailsenderimpl MailSender = new Javamailsenderimpl (); Mailsender.sethost ( "smtp.163.com"); Specifies the mail server hostname mailsender.setport (25) used to send email; "[email protected]"); "test"); return MailSender;}}
It is important to note that if you use the 163 mail server, you must turn on SMTP in the settings.
Assemble and use the mail transmitter
@RunWith (Springjunit4classrunner.class)@ContextConfiguration (Classes={rootconfig.class, Webconfig.class})@WebAppConfigurationPublicClassemailsendertest {@Autowired private Javamailsender mailsender; @Test public void Sendsimpleemail () {simplemailmessage message = new Simplemailmessage (); Message Builder Message.setfrom ("[email protected]"); Sender Message.setto ("[email protected]"); Recipient Message.setsubject ("Spring Email Test"); Subject Message.settext ("Hello world!!"); //Text mailsender.send (message); SYSTEM.OUT.PRINTLN ("message Sent");}}
Here is the message received:
Build rich content email messages to add attachments
To send an email with an attachment, the key technique is to create a multipart type of message--email composed of several parts, one of which is the email body and the other part is the attachment.
In order to send a multipart type of email, you need to create a MIME (multipurpose Internet Mail Extensions) message.
/** * Send an email with an attachment *@throws messagingexception * *@TestPublicvoidSendemailwithattachment ()Throws messagingexception{MimeMessage message = Mailsender.createmimemessage (); Mimemessagehelper helper =new Mimemessagehelper (message, true); Constructs the message helper, the second parameter indicates that the message is multipart type helper.setfrom ("[email protected]"); Helper.setto ("[email protected] "); Helper.setsubject ("Spring Email Test"); Helper.settext ("This is a message with an attachment"); //Use spring's filesystemresource to load fox.png filesystemresource image = new Filesystemresource ("D:\\fox.png" ); System.out.println (Image.exists ()); Helper.addattachment ("fox.png", image); Add attach, the first parameter is the name of the attachment added to the email, the second person parameter is the picture resource mailsender.send (message); SYSTEM.OUT.PRINTLN ("message Sent");}
The API of Javax.mail.internet.MimeMessage itself is somewhat cumbersome. Spring provides us with a mimemessagehelper to help us by instantiating it and passing mimemessage to its constructor.
Results:
Send Rich text content to email
Here we use an embedded image:
/** * Send Rich text content email *@throws messagingexception * *@TestPublicvoidSendrichemail ()Throws messagingexception{MimeMessage message = Mailsender.createmimemessage (); Mimemessagehelper helper =New Mimemessagehelper (Message,true); Helper.setfrom ("[email protected]"); Helper.setto ("[email protected]"); Helper.setsubject ("Spring email Test") helper.settext ("' " </body>true); The second parameter indicates that this is an HTML //src= ' Cid:testlogo ' indicating that a part of the message is a picture and is identified with Testlogo classpathresource image = New Classpathresource ("logo.jpg"); System.out.println (Image.exists ()); Helper.addinline ("Testlogo", image); To add an inline picture, the first parameter indicates the identifier of the inline picture, and the second parameter is the picture's resource reference mailsender.send (message); }
Results:
Generate email using a template use velocity to build an email message
Apache velocity is a generic template engine provided by Apache.
Configure the Velocityengine factory bean, which makes it easy to generate velocityengine in the context of the spring application:
/** * 配置VelocityEngine工厂Bean * @return */ @Bean public VelocityEngineFactoryBean velocityEngine() { VelocityEngineFactoryBean velocityEngine = new VelocityEngineFactoryBean(); Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.setVelocityProperties(props); return velocityEngine; }
Here we configure it to load the velocity template from the Classpath
Use:
@Autowired Velocityengine Velocityengine;@SuppressWarnings ("Deprecation")@TestPublicvoidSendemailbyvelocity ()Throws messagingexception{map<string, object> modal =New hashmap<string, object> (); Modal.put ("Name","Xue Xiao Qiang"); Modal.put ("Text","This is a template created with velocity");Use Velocityengineutils to combine the velocity template with the model data into a string string emailtext = Velocityengineutils. Mergetemplateintostring ( Velocityengine, "EMAILTEMPLATE.VM", "UTF-8", modal); MimeMessage message = Mailsender.createmimemessage (); //the third parameter setting encoding, otherwise if there is a character garbled problem mimemessagehelper helper = new Mimemessagehelper (message, true, "[email protected]"); Helper.setto ( "[email protected]"); Helper.setsubject (true); Classpathresource image = new classpathresource ( "logo.jpg"); Helper.addinline ( "Mail Sent");}
Here the template Emailtemplate.vm file contents are:
<!DOCTYPE html><html><body><img src=‘cid:logo‘><h4>Hello ${name}</h4><h3>${text}</h3></body></html>
Results:
Configure spring to send mail