Spring Learning notes use spring to send email

Source: Internet
Author: User
configure spring to send mail

The core of Spring email abstraction is the MailSender interface. As the name suggests, the implementation of MailSender can connect email server to achieve the function of sending mail.

Spring is a MailSender implementation--javamailsenderimpl with its own. It uses the JavaMail API to send email. Configure mail Senders

Core maven Required:

     <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>
    </dependency>

Configuration bean:

public class RootConfig {

    /**
     * Configure mail transmitter * @return * * *
     @Bean public
    MailSender MailSender () {
        Javamailsenderimpl MailSender = new Javamailsenderimpl ();
        Mailsender.sethost ("smtp.163.com");//Specify the mail server host name
        Mailsender.setport (25) for sending email;//default port, standard SMTP port
        Mailsender.setusername ("test@163.com");//username
        mailsender.setpassword ("test");//password return
        MailSender
    }

}

It is important to note that if you use the 163 mail server, be sure to turn on SMTP in the settings. assemble and use a mail transmitter

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (Classes={rootconfig.class, Webconfig.class})
@WebAppConfiguration Public
class Emailsendertest {

    @Autowired
    private Javamailsender mailsender;

    @Test public
    void Sendsimpleemail () {
        simplemailmessage messages = new Simplemailmessage ();//Message Builder
        Message.setfrom ("test@163.com");//Sender
        Message.setto ("shoujian@tom.com");//Recipient
        Message.setsubject (" Spring Email Test ");//Subject
        Message.settext (" Hello world!! "); /text
        mailsender.send (message);
        SYSTEM.OUT.PRINTLN ("Send mail Complete");
    }

Here are the messages you receive:
build a rich content email message Add Attachment

To send an email with an attachment, the key trick is to create a multipart type of message--email composed of several parts, some of which are email bodies, and other parts are attachments.
To send a multipart type of email, you need to create a MIME (multipurpose Internet Mail Extensions) message.

/** * Send email with attachment * @throws messagingexception/@Test public void Send
        Emailwithattachment () throws messagingexception{mimemessage message = Mailsender.createmimemessage (); Mimemessagehelper helper = new Mimemessagehelper (message, true);//constructs the messaging helper, and the second argument indicates that the message is multipart type HELPER.SETFR
        Om ("testFrom@163.com");
        Helper.setto ("testTo@qq.com");
        Helper.setsubject ("Spring Email Test");
        Helper.settext ("This is a message with attachments");
        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 additional, the first parameter is the name added to the attachment in email, the second person parameter is the picture resource mailsender.send (message);
    SYSTEM.OUT.PRINTLN ("Send mail Complete"); }

The API for Javax.mail.internet.MimeMessage itself is a bit unwieldy. Spring provides us with Mimemessagehelper to help us by simply instantiating it and passing mimemessage to its builder.
Results:
send email with rich text content

Here we use the embedded picture:

/** * Send Rich text content email * @throws messagingexception/@Test public void Sen
        Drichemail () throws messagingexception{mimemessage message = Mailsender.createmimemessage ();
        Mimemessagehelper helper = new Mimemessagehelper (message, true);
        Helper.setfrom ("testFrom@163.com");
        Helper.setto ("testTo@qq.com");
        Helper.setsubject ("Spring Email Test"); Helper.settext ("

Results:
generate email using templates building email messages using velocity

Apache velocity is a generic template engine provided by Apache.
Configures the Velocityengine factory Bean, which facilitates the generation of velocityengine in the Spring application context:

/**
     * Configure Velocityengine factory 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") @Test public void sendemailbyvelocity () throws messagingexception{Map&lt ;
        String, object> modal = new hashmap<string, object> ();
        Modal.put ("name", "Xue Xiao Qiang");
        Modal.put ("text", "This is a template generated by velocity"); Use Velocityengineutils to combine the velocity template with the model data into string string emailtext = Velocityengineutils. mergetemp

        Lateintostring (Velocityengine, "EMAILTEMPLATE.VM", "UTF-8", modal);
        MimeMessage message = Mailsender.createmimemessage ();
        The third parameter sets the code, otherwise if there are characters will appear garbled problem mimemessagehelper helper = new Mimemessagehelper (message, True, "utf-8");
        Helper.setfrom ("testForm@163.com");
        Helper.setto ("testTo@qq.com");
        Helper.setsubject ("Spring Email Test");
        Helper.settext (Emailtext, true);
        Classpathresource image = new Classpathresource ("logo.jpg");
        Helper.addinline ("logo", image); MailSender.Send (message);
    SYSTEM.OUT.PRINTLN ("Send mail Complete"); }

Here the template Emailtemplate.vm file contents are:

<! DOCTYPE html>

Results:

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.