[Spring] Send emails using Spring and send emails using spring

Source: Internet
Author: User

[Spring] Send emails using Spring and send emails using spring

The core of Spring Email abstraction is the MailSender interface. The MailSender can be connected to the Email server to implement the mail sending function, such:

The implementation of a MailSender in Spring is JavaMailSenderImpl, which also uses the JavaMail API to send an Email. before using it, you must first assemble JavaMailSenderImpl into a bean in the Spring application context, as shown below:

@Beanpublic MailSender mailSender (Environment env) {    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();    mailSender.setHost(env.getProperty("mailserver.host"));        return mailSender;}

By default, JavaMailSenderImpl assumes that the mail server listens to port 25. If the mail server listens to different ports, you can use the port attribute to specify the port number. In the preceding mailSender () method, add:

mailSender.setPort(env.getProperty("mailserver.port"));

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

mailSender.setUsername(env.getProperty("mailserver.username"));mailSender.setPassword(env.getProperty("mailserver.password"));

In this way, JavaMailSenderImpl has been configured. Now you can create your own mail session. If javax has been configured in JNDI. mail. you do not need to configure detailed server details for JavaMailSenderImpl for MailSession. You can configure it to use the ready MailSession in JNDI.

When JndiObjectFactoryBean is used, you can configure a Bean in the @ bean method as follows, which searches for MailSession from JNDI:

@Beanpublic JndiObjectFactoryBean mailSession ( ) {    JndiObjectFactoryBean jndi = new JndiObjectFactoryBean();    jndi.setJndiName("mail/Session");    jndi.setProxyInterface(MailSession.class);    jndi.setResourceRef(true);        return jndi;}

Then, you can use the <jee: jndi-lookup> element of Spring to obtain an object from JNDI. Here, you can use <jee: jndi-lookup> to create a bean, it references the mail session in JNDI:

<jee:jndi-lookup id="mailSession" jndi-name="mail/Session" resource-ref="true">

After the email session is ready, you can assemble it into the mailSender bean:

@Beanpublic MailSender mailSender (MailSession mailSession) {    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();    mailSender.setSession(mailSession);        return mailSender;}

By assembling the mail session to the session attribute of JavaMailSenderImpl, the original server configuration is completely replaced. Now, the mail session is completely configured and managed through JNDI, javaMailSenderImpl can focus on sending emails without having to process the email server on its own.

Then we need to assemble mailSender into our business layer implementation class (assuming SpitterEmailServiceImpl class), as follows:

@AutowiredJavaMailSender mailSender;

Then I want to send an Email to the Spitter user prompting his friend to write a new Spittle. At this time, I need a method to send an Email. This method should accept the Email address and Spittle object information, you can use the email sender to complete this function as follows:

Public void sendSimpleSpittleEmail (Stirng to, Spittle spittle) {SimpleMailMessage message = new SimpleMailMessage (); String spitterName = spittle. getSpitter (). getFullName (); message. setFrom ("... @ spitter.com "); // email Address message. setTo (to); message. setSubject ("New spittle from" + spitterName); message. setText (spitterName + "says:" + spittle. getText (); mailSender. send (message );}

The last step in the code above is to pass the message to the send () method of the mail sender, so that the mail will be sent out.

 

Send Email with attachment

The message is successfully sent. Now, try to send an Email with an attachment. To send an attachment, create a multipart message. The Email consists of multiple parts, one of which is the Email body, the other part is the attachment. To send a multipart Email, you need to create a MIME message. You can start with the createMimeMessage () method of the mail Sender:

MimeMessage message = mailSender.createMimeMessage();

However, the API using javax. mail. internet. MimeMessage is a little complicated here. You can use the MimeMessageHelper provided by Spring for simple operations and pass MimeMessage to it when instantiating it.

MimeMessageHelper helper = new MimeMessageHelper (message, true); // true indicates multipart

After obtaining the MimeMessageHelper instance, you can start assembling the Email message:

String spitterName = spittle.getSpitter().getFullName();helper.setForm("...@spitter.com");helper.setTo(to);helper.setSubject("New spittle from " + spitterName);helper.setText(spitterName + " says: " +spittle.getText());

Add the attachment below. Take the image as an example. You only need to pass this resource to the addAttachment method of helper:

FileSystemResource image = new FileSystemResource("/file/test.png"); helper.addAttachment("test.png", image);

Use springfilesystemresourceto access test.png under the class, and then call addAttachment (). The first parameter is the name of the attachment to be added to the Email, and the second parameter is the resource file.

Here, the multipart type Email has been constructed. Now we need to use MimeMessageHelper to send an Email with an attachment. The complete code is as follows:

public void sendSpittleEmailWithAttachment (Stirng to, Spittle spittle) throws MessagingException {    MimeMessage message = mailSender.createMimeMessage();    MimeMessageHelper helper = new MimeMessageHelper(message, true);    String spitterName = spittle.getSpitter().getFullName();    helper.setForm("...@spitter.com");    helper.setTo(to);    helper.setSubject("New spittle from " + spitterName);    helper.setText(spitterName + " says: " +spittle.getText());    FileSystemResource image = new FileSystemResource("/file/test.png");     helper.addAttachment("test.png", image);    mailSender.send(message);}

At this point, an Email with an attachment is successfully sent.

 

Note: For more articles, see the public account Id weknow619.

 

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.