You can send e-mails in code.

Source: Internet
Author: User

The messages that are sent include the following:

    1. from field--to indicate the sender
    2. To field--to indicate the recipient
    3. subject Field--to describe the subject of the message
    4. cc field-CC, send the message to the recipient and copy it to another recipient who can see who the message was copied to
    5. bcc field--secret send, send the message to the recipient while secretly sending the message to another recipient, the recipient cannot see who the message was sent to

The message body refers to the specific content of the message.

Create and send messages using JavaMail

The messages created by JavaMail are based on the MIME protocol. So you can use JavaMail to create complex messages that contain images and attachments.

A brief introduction to the MIME protocol

In our actual development, an e-mail message may contain both images and attachments, in which case the message format specified in the RFC882 document will not be able to meet the requirements.

  The MIME protocol is an upgrade and supplement to the RFC822 document , which describes how to produce a complex message. Usually we refer to the MIME protocol as a MIME message . the data described by the MIME protocol is called a MIME message.
For a complex message, if you have multiple different data, the MIME protocol specifies that you want to delimit multiple pieces of data using a separator, and use the Content-type header field to describe the type of data and the relationships between multiple data.

A brief introduction to the JavaMail API

  

Send a simple message that contains only text
  Package me.gacl.main;  Import java.util.Properties;  Import Javax.mail.Message; Import javax.mail.Session;  Import Javax.mail.Transport;  Import javax.mail.internet.InternetAddress;    Import Javax.mail.internet.MimeMessage;  public class Sendmail {/** * @param args * @throws Exception */public static void main (string[]         args) throws Exception {Properties prop = new Properties ();         Prop.setproperty ("Mail.host", "smtp.sohu.com");         Prop.setproperty ("Mail.transport.protocol", "SMTP");         Prop.setproperty ("Mail.smtp.auth", "true");         5 Steps to send a message using JavaMail//1, creating session Session Session = Session.getinstance (prop);         Turn on the session debug mode, so that you can see the program send email running status Session.setdebug (true);         2, through session to get Transport object Transport ts = Session.gettransport ();         3, the user name and password to use the mailbox to connect to the mail server, when sending a message, the sender needs to submit the mailbox user name and password to the SMTP server, the user name and password are verified before you can send the message to the recipient normally. Ts.connect ("smtp.sohu.com", "GACL "," email password ");         4. Create mail Message message = Createsimplemail (session);         5, Send mail ts.sendmessage (message, message.getallrecipients ());     Ts.close ();          } public static MimeMessage Createsimplemail (Session session) throws Exception {//Create mail Object         MimeMessage message = new MimeMessage (session);         Indicates the sender of the message Message.setfrom (new InternetAddress ("[email protected]")); Indicates the recipient of the message, and now the sender and the recipient are the same, that is, they send themselves message.setrecipient (Message.RecipientType.TO, New InternetAddress ("[Email&nbs         P;protected]);         The title of the message Message.setsubject ("Simple Mail with Text only"); The text content of the message message.setcontent ("Hello!        "," text/html;charset=utf-");     Returns the created Message object return message; }}

Send a message with a picture

 Package me.gacl.main;  Import Java.io.FileOutputStream;    Import java.util.Properties;  Import Javax.activation.DataHandler; Import Javax.activation.FileDataSource;  Import Javax.mail.Message; Import javax.mail.Session; Import Javax.mail.Transport; Import javax.mail.internet.InternetAddress; Import Javax.mail.internet.MimeBodyPart; Import Javax.mail.internet.MimeMessage;  Import Javax.mail.internet.MimeMultipart; public class Sendmail {public static void main (string[] args) throws Exception {Properties prop         = new Properties ();         Prop.setproperty ("Mail.host", "smtp.sohu.com");        Prop.setproperty ("Mail.transport.protocol", "SMTP");         Prop.setproperty ("Mail.smtp.auth", "true");         5 Steps to send a message using JavaMail//1, creating session Session Session = Session.getinstance (prop);        Turn on the session debug mode, so that you can see the program send email running status Session.setdebug (true); 2, through session to get Transport object Transport ts = Session.gettransport ();         3, connected to the mail server, the sender is required to provide the user name and password to verify Ts.connect ("smtp.sohu.com", "GaCl", "email password");         4. Create mail Message message = Createimagemail (session);         5, Send mail ts.sendmessage (message, message.getallrecipients ());     Ts.close (); } public static MimeMessage Createimagemail (Session session) throws Exception {//Create message Mimemes         Sage message = new MimeMessage (session);         Set basic message information//sender Message.setfrom (New InternetAddress ("[email protected]"));         Recipient Message.setrecipient (Message.RecipientType.TO, New InternetAddress ("[email protected]"));          Message title Message.setsubject ("Mail with Pictures");         Prepare message data//Prepare message body data MimeBodyPart text = new MimeBodyPart ();         Text.setcontent ("This is a message body with pictures  Mail", "text/html;charset=utf-8");         Prepare picture data MimeBodyPart image = new MimeBodyPart (); DataHandler dh = new DataHandler (nEW Filedatasource ("src\\1.jpg"));         Image.setdatahandler (DH);         Image.setcontentid ("xxx.jpg");         Describes the data relationship mimemultipart mm = new Mimemultipart ();        Mm.addbodypart (text);         Mm.addbodypart (image);          Mm.setsubtype ("related");         Message.setcontent (mm);         Message.savechanges ();         Write the created message to the E disk to save Message.writeto (new FileOutputStream ("E:\\imagemail.eml") in the form of a file;     Returns the message that was created. } }

Send a message with an attachment

Package Cn.bdqn;import Java.io.ioexception;import Javax.mail.messagingexception;import Javax.mail.internet.mimemessage;import Javax.mail.internet.mimeutility;import Org.springframework.core.io.classpathresource;import Org.springframework.mail.javamail.javamailsender;import Org.springframework.mail.javamail.mimemessagehelper;public class Mailwithattachment {private JavaMailSender     MailSender;    public void Setmailsender (Javamailsender mailsender) {this.mailsender = MailSender; } public void Send () throws messagingexception,ioexception{mimemessage mimemessage = Mailsender.createmimem        Essage ();        Mimemessagehelper helper = new Mimemessagehelper (MimeMessage, True, "UTF-8");        Helper.setfrom ("[email protected]");                Helper.setto ("[email protected]");        Helper.setsubject ("haha");             Helper.settext ("hehe"); Classpathresource file1 = new Classpathresource ("/cn/bdqn/attachfilEs/test.doc ");                Helper.addattachment (File1.getfilename (), File1.getfile ());        Classpathresource file2 = new Classpathresource ("/cn/bdqn/attachfiles/test.doc");        Helper.addattachment (Mimeutility.encodeword (File2.getfilename ()), File2.getfile ());    Mailsender.send (MimeMessage); }}

Large configuration:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd "> <bean id=" mailsender "class=" Org.springframework.mail.javamail.JavaMailSenderImpl " > <property name= "host" value= "192.168.8.71" ></property><!--Server--<property name= "Port" value= "></property><!--Ports--<property name=" username "value=" [email protected] " ></property><!--Username--<property name= "password" value= "FSB" ></property><!--password--&        Gt <property name= "Protocol" value= "SMTP" ></property><!--protocol and <property name= "defaultencoding  "Value=" Utf-8 "></property><!--Default code--      <property name= "Javamailproperties" > <props> <!--setting up an SMTP server requires user authentication-- <prop key= "Mail.smtp.auth" >true</prop> </props> </property> &lt ;/bean> <bean id= "mailwithattachment" class= "cn.bdqn.MailWithAttachment" > <property name= "mailse NDEr "ref=" MailSender "></property> </bean></beans>

Test:

Package Cn.bdqn;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class MailTest {public    static void Main (string[] args) {        ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");                try{            mailwithattachment Mailwithattach = (mailwithattachment) context.getbean ("Mailwithattachment");            Mailwithattach.send ();            SYSTEM.OUT.PRINTLN (0);        } catch (Exception e) {            System.out.print (e.tostring ());        }    }

You can send e-mails in code.

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.