Java uses spring Javamailsenderimpl to send messages that support plain text, attachments, HTML, velocity templates

Source: Internet
Author: User
Tags html header

Java uses spring Javamailsenderimpl to send messages that support plain text, attachments, HTML, velocity templates Blog Category:
    • Java
    • Spring

This article mainly introduces the use of Javamailsenderimpl to send mail. The general message is sent first, followed by the sending of rich Text (HTML) messages and the use of velocity as a template for sending messages.

Message delivery is divided into three steps: creating a Mail sender , writing a message, and sending a message .

Spring's Javamailsenderimpl provides powerful mail-sending capabilities for sending plain text messages, email with attachments, HTML-formatted messages, email with pictures, setting the Send content encoding format, and setting the sender's display name.

As described below, many of the sample code are hard-coded strings, and it is recommended that you use spring's configuration file for the actual use.

1. Create a mail transmitter

First define the Javamailsenderimpl object, and the SMTP related information settings, the equivalent of our own mailbox, as follows:

Java code
    1. Javamailsenderimpl MailSender = new Javamailsenderimpl ();
    2. Mailsender.sethost ("smtp.qq.com");
    3. Mailsender.setusername ("[email protected]");
    4. Mailsender.setpassword ("asterisks");
Javamailsenderimpl MailSender = new Javamailsenderimpl () mailsender.sethost ("smtp.qq.com"); Mailsender.setusername ( "[Email protected]"); Mailsender.setpassword ("asterisks");

Of course, the better way is to use the configuration file configuration, here is just introduction, ignoring hard coding first.

The above host is the mailbox service SMTP address, user name, password for the user's own mailbox. In addition to the above, you can also set

Setport (int port), Setprotocol (String protocol), etc., can be temporarily not considered.

So we've created a mail sender like this.

2, start to write mail, write the contents of the message

Javamailsenderimpl SupportMimeMessages和SimpleMailMessages。

MimeMessages为复杂邮件模板,支持文本、附件、html、图片等。

Simplemailmessages implements the Mimemessagehelper, which supports text for regular mail templates.

Let's take simplemailmessages as an example to introduce

Java code
    1. Simplemailmessage SMM = new Simplemailmessage ();
    2. Set Message parameters
    3. Smm.setfrom (Mailsender.getusername ());
    4. Smm.setto ("[email protected]");
    5. Smm.setsubject ("Hello World");
    6. Smm.settext ("Hello World via Spring Mail Sender");
    7. Send mail
    8. Mailsender.send (SMM);
Simplemailmessage SMM = new Simplemailmessage ();//Set Mail parameters Smm.setfrom (mailsender.getusername ()); Smm.setto ("[Email Protected], smm.setsubject ("Hello World"), Smm.settext ("Hello World via Spring Mail Sender");//Send mail Mailsender.send ( SMM);

In this way, we have completed the writing of a Simple mail, for complex mail, writing and sending the following

Java code
  1. Pay for more complex message formats and content using JavaMail's MimeMessage
  2. MimeMessage msg = Mailsender.createmimemessage ();
  3. Create a Mimemessagehelper object to handle MimeMessage helper classes
  4. Mimemessagehelper helper = new Mimemessagehelper (msg, true);
  5. Setting parameters with auxiliary class MimeMessage
  6. Helper.setfrom (Mailsender.getusername ());
  7. Helper.setto ("[email protected]");
  8. Helper.setsubject ("Hello Attachment");
  9. Helper.settext ("This was a mail with attachment");
  10. Load the file resource as an attachment
  11. Classpathresource file = new Classpathresource ("chrysanthemum.jpg");
  12. Add to Attachment
  13. Helper.addattachment ("attachment.jpg", file);
  14. Send mail
  15. Mailsender.send (SMM);
Use JavaMail's mimemessage to pay for more complex message formats and content mimemessage msg = Mailsender.createmimemessage ();//Create Mimemessagehelper objects, Helper classes that handle mimemessage mimemessagehelper helpers = new Mimemessagehelper (msg, true);//Use auxiliary class MimeMessage to set parameters Helper.setfrom ( Mailsender.getusername ()); Helper.setto ("[email protected]"); Helper.setsubject ("Hello Attachment"); Helper.settext ("This was a mail with Attachment");//Load file resource as Attachment Classpathresource file = new Classpathresource ("chrysanthemum.jpg");// Add Attachment helper.addattachment ("attachment.jpg", file);//Send mail Mailsender.send (SMM);

Where Mimemessagehelper is the auxiliary class mimemessages. The above contains a resource file as an attachment for sending. For normal file sending methods are as follows:

Java code
    1. Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg");
    2. Helper.addinline ("file", file);
Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg"); Helper.addinline ("File", file);

3. Send mail

2 already contains the sent code, just use the Javamailsenderimpl send interface. Support Type is

Java code
  1. void Send (MimeMessage mimemessage)
  2. Send the given JavaMail MIME message.
  3. void Send (mimemessage[] mimemessages)
  4. Send the given array of JavaMail MIME messages in batch.
  5. void Send (Mimemessagepreparator mimemessagepreparator)
  6. Send the JavaMail MIME message prepared by the given Mimemessagepreparator.
  7. void Send (mimemessagepreparator[] mimemessagepreparators)
  8. Send the JavaMail MIME messages prepared by the given mimemessagepreparators.
  9. void Send (Simplemailmessage simplemessage)
  10. Send the given Simple mail message.
  11. void Send (simplemailmessage[] simplemessages)
  12. Send the given array of Simple mail messages in batch.
Voidsend (mimemessage mimemessage)           Send The given JavaMail MIME message. Voidsend (mimemessage[] mimemessages)           Send the given array of JavaMail MIME messages in batch. Voidsend (mimemessagepreparator mimemessagepreparator)           Send the JavaMail MIME message prepared by the given Mimemessagepreparator. Voidsend (mimemessagepreparator[] mimemessagepreparators)           Send the JavaMail MIME messages prepared by the given Mimemessagepreparators. Voidsend (simplemailmessage simplemessage)           Send The given Simple mail message. Voidsend (simplemailmessage[] Simplemessages)           Send The given array of Simple mail messages in batch.

Here's how to send a rich text file and send a message using velocity as a template.

4. Send HTML file

It is only necessary to set the HTML to True when Mimemessagehelper settext. SetText introduced as follows:

XML code
    1. SetText (String text, Boolean html)
    2. Set the given text directly as content in Non-multipart mode or as default body part in multipart mode.
SetText (String text, boolean html)           Set the given text directly as content in Non-multipart mode or as default body par T in multipart mode.

The sample code (including attachments) is as follows:

Java code
    1. //the second parameter true, indicating that the contents of text are HTML   
    2. //note tag, src= ' Cid:file ', ' CID ' is the abbreviation for ContentID, ' file ' is a marker, You need to call Mimemessagehelper's Addinline method in a later code to replace the file   
    3. helper.settext (true);   
    4. filesystemresource file = new  Filesystemresource ( "c:\\users\\image1.jpg");   
    5. Helper.addinline (
The second parameter, True, indicates that the content of text is html//note  tag, src= ' Cid:file ', ' CID ' is the abbreviation for ContentID, ' file ' is a token, You need to call Mimemessagehelper's Addinline method in a later code to replace the file Helper.settext ("<body><p>hello Html email</p>< IMG src= ' cid:file '/></body> ", true); Filesystemresource file = new Filesystemresource ("c:\\users\\image1.jpg"); Helper.addinline ("File", file);

5. Send a message using velocity as a template

Using the velocity template, you need the velocity jar package, which can be downloaded on the official website and added to Classpath.

The principle of sending a message using velocity as a template is as follows:

A similar to web programming, the velocity as the front end, in Java to set the value of the variables to be displayed in the VM

B convert VM content to text using Velocityengineutils's mergetemplateintostring function

C Send a message as you send an HTML message with 4

So the most important process will be to convert the contents of the VM to a string, that is, to set the message content, the other is not different from the above

5.1 Create a new VM file named INDEX.VM

Java code
    1. <body>
    2. <div>${user} </div>
    3. <div>${content}</div>
    4. </body>
    5. "Background-color: #ffffff; White-space:normal "> </SPAN>

The HTML header definition is omitted for convenience.
Where ${user} is the velocity syntax, the equivalent of a variable, in a Java program can set the value of this variable in the front-end display.

5.2 Creating a Velocityenginefactorybean object and setting properties

Java code
    1. The parameters of velocity, created velocityengine through Velocityenginefactorybean, are also recommended in the configuration file
    2. Properties Properties = System.getproperties ();
    3. Properties.put ("Resource.loader", "class");
    4. Properties.put ("Class.resource.loader.class", "   Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader ");
    5. Velocityenginefactorybean v = new Velocityenginefactorybean ();
    6. V.setvelocityproperties (properties);
The velocity parameter, created by Velocityenginefactorybean Velocityengine, is also recommended in the configuration file for the properties properties System.getproperties ();p roperties.put ("Resource.loader", "class");p roperties.put ("Class.resource.loader.class", "Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocityenginefactorybean v = new Velocityenginefactorybean (); V.setvelocityproperties (properties);

5.3 Convert VM content to normal string

Java code
    1. //  declares the Map object and fills in the key-value pairs used to populate the template file   
    2. map< String, string> model = new hashmap<string, string > ();   
    3. model.put (
    4. model.put (
    5. // spring provides the velocityengineutils to populate the template with data and converted to a normal String object   
    6. string emailtext =  Velocityengineutils.mergetemplateintostring (Velocityengine,  "INDEX.VM",  model);   
Declare the Map object and fill in the key values used to populate the template file with the map<string, string> model = new hashmap<string, string> (); Model.put ("User", "ooo Model.put ("Content", "Nihao");//spring provides the velocityengineutils to populate the template with data and convert it to a normal string object string Emailtext = Velocityengineutils.mergetemplateintostring (Velocityengine, "INDEX.VM", model);

This allows us to populate the variable values in the VM and convert the content to string

5.4 Set message content, same as 4

Java code
    1. Helper.settext (Emailtext, true);
Helper.settext (Emailtext, true);

Other content is the same as the above 1, 2, 3 process.

Note: The VM file format needs to be consistent with the message encoding or it will appear garbled

Java uses spring Javamailsenderimpl to send messages that support plain text, attachments, HTML, velocity templates

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.