Javaweb Learning Summary (52)--Create and send messages using JavaMail

Source: Internet
Author: User

Javaweb Learning Summary (52)--Create a message and send a message using JavaMail simple description of the RFC882 document

The RFC882 document specifies how to write a simple message (plain text message), a simple message containing two parts of the message header and the message body, separated by a blank line between the message header and the message body.

The message header contains 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.

Second, the MIME protocol simple Introduction

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.

Iii. using JavaMail to create messages and send messages

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.

3.1. Simple introduction of JavaMail API

  

  

  

3.2. Create a message to send a test project

  

3.3. Send a simple e-mail message containing only text
 1 package me.gacl.main; 2 3 Import java.util.Properties; 4 Import Javax.mail.Message; 5 Import javax.mail.Session; 6 Import Javax.mail.Transport; 7 Import javax.mail.internet.InternetAddress; 8 Import Javax.mail.internet.MimeMessage; 9/**11 * @ClassName: Sendmail12 * @Description: Send Email13 * @author: Aloof and Pale wolf * @date: 2015-1-12 PM 9:42:5615 *16 */P Ublic class Sendmail {/**20 * @param args21 * @throws Exception */23 public static void Ma In (string[] args) throws Exception {Prop.setproperty Properties prop = new Properties (); Mail.host "," smtp.sohu.com "), Prop.setproperty (" Mail.transport.protocol "," SMTP "), Prop.setproperty (" M Ail.smtp.auth "," true "); 29//5 steps to send a message using JavaMail 30//1, creating a session31 session session = Session.getin Stance (prop); 32//Open session debug mode, so you can see the program send email running status of Session.setdebug (true); 34//2, through Sessi On Get transport Object TRANSPORT ts = Session.gettransport (); 36//3, using the user name and password of the mailbox to connect to the mail server, when sending a message, the sender needs to submit the user name and password of the mailbox to the SMTP server, the user name and password are verified before they can send the message to the recipient normally People. PNS Ts.connect ("smtp.sohu.com", "GaCl", "E-mail Password"), 38//4, create mail message = Createsimplemail (SE     ssion); 40//5, Send mail ts.sendmessage (message, message.getallrecipients ()); Ts.close (); 43}44 /**46 * @Method: createSimpleMail47 * @Description: Create a message that contains only text * @Anthor: Aloof Wolf 49 *50 * @  Param session51 * @return52 * @throws Exception53 * * static mimemessage Createsimplemail (Session         session) throws Exception {56//Create mail object mimemessage message = new MimeMessage (session); 58 Indicates the sender of the message Message.setfrom (new InternetAddress ("[email protected]")); 60//Specify the recipient of the message, now sender and receiver The person is the same, that is oneself to send to oneself the message.setrecipient (Message.RecipientType.TO, New InternetAddress ("[email protected]")); 6    2//title of the message 63     Message.setsubject ("Simple Mail with Text only"); 64//Message text content message.setcontent ("Hello!" "," Text/html;charset=utf-8 "); 66//Return to the Created mail object. message;68 return}69}
3.4. Send messages with inline images
 1 package me.gacl.main; 2 3 Import Java.io.FileOutputStream; 4 Import java.util.Properties; 5 6 Import Javax.activation.DataHandler; 7 Import Javax.activation.FileDataSource; 8 Import Javax.mail.Message; 9 Import javax.mail.session;10 Import javax.mail.transport;11 import javax.mail.internet.internetaddress;12 Import JAVAX.MAIL.INTERNET.MIMEBODYPART;13 Import javax.mail.internet.mimemessage;14 Import Javax.mail.internet.mimemultipart;15/**17 * @ClassName: Sendmail18 * @Description: Send Email19 * @author: Aloof Wolf * @date      : 2015-1-12 PM 9:42:5621 *22 * * * public class Sendmail {/**26 * @param args27 * @throws Exception 28 */29 public static void Main (string[] args) throws Exception {Properties prop = new Propert IES (), Prop.setproperty ("Mail.host", "smtp.sohu.com"), Prop.setproperty ("Mail.transport.protocol", "SM TP "), Prop.setproperty (" Mail.smtp.auth "," true "); 35//5 steps to send a message using JavaMail 36//1, create session37 Session session = Session.getinstance (prop), 38//Open session debug mode, so that you can see the program send email running status 39         Session.setdebug (TRUE); 40//2, Get Transport object through session Transport ts = Session.gettransport (); 42         3, connected to the mail server, the sender is required to provide the user name and password for the mailbox to verify Ts.connect ("smtp.sohu.com", "GaCl", "email password"); 44//4, create message 45 Message message = Createimagemail (session); 46//5, Send message ts.sendmessage (message, message.getallrecipients (      ); Ts.close ();}50/**52 * @Method: createImageMail53 * @Description: Generate a message with pictures in the body 54  * @Anthor: Aloof Wolf *56 * @param session57 * @return58 * @throws Exception59 * */public static MimeMessage Createimagemail (Session session) throws Exception {61//Create message MimeMessage message = new Mime Message (session); 63//Set basic information for a message 64//Sender of Message.setfrom (New InternetAddress ("[Email protec Ted]); 66//RecipientMessage.setrecipient (Message.RecipientType.TO, New InternetAddress ("[email protected]")); 68//Mail Header Message.setsubject ("Mail with Pictures"); 70 71//Prepare mail Data 72//Prepare message body data MimeBodyPart text = new Mi         Mebodypart (); Text.setcontent ("This is an e-mail message with pictures  Mail", "Text/html;charset=utf-8"); 75 Prepare picture data MimeBodyPart image = new MimeBodyPart (); DataHandler dh = new DataHandler (New Filedatasou         Rce ("src\\1.jpg")); Image.setdatahandler (DH), Image.setcontentid ("xxx.jpg"); 80//Description Data Relationship 81 Mimemultipart mm = new Mimemultipart (), Mm.addbodypart (text), Mm.addbodypart (image), MM . Setsubtype ("related"); message.setcontent (mm); Message.savechanges (); 88//writes the created message to the E-drive file form to save the Message.writeto (new FileOutputStream ("e:\\imagemail.eml")); 90//return message created ; 92}93}
3.5. Send mail with Attachments
 1 package me.gacl.main; 2 3 Import Java.io.FileOutputStream; 4 Import java.util.Properties; 5 6 Import Javax.activation.DataHandler; 7 Import Javax.activation.FileDataSource; 8 Import Javax.mail.Message; 9 Import javax.mail.session;10 Import javax.mail.transport;11 import javax.mail.internet.internetaddress;12 Import JAVAX.MAIL.INTERNET.MIMEBODYPART;13 Import javax.mail.internet.mimemessage;14 Import Javax.mail.internet.mimemultipart;15/**17 * @ClassName: Sendmail18 * @Description: Send Email19 * @author: Aloof Wolf * @date      : 2015-1-12 PM 9:42:5621 *22 * * * public class Sendmail {/**26 * @param args27 * @throws Exception 28 */29 public static void Main (string[] args) throws Exception {Properties prop = new Propert IES (), Prop.setproperty ("Mail.host", "smtp.sohu.com"), Prop.setproperty ("Mail.transport.protocol", "SM TP "), Prop.setproperty (" Mail.smtp.auth "," true "); 35//5 steps to send a message using JavaMail 36//1, create session37 Session session = Session.getinstance (prop), 38//Open session debug mode, so that you can see the program send email running status 39         Session.setdebug (TRUE); 40//2, Get Transport object through session Transport ts = Session.gettransport (); 42 3, connected to the mail server Ts.connect ("smtp.sohu.com", "GaCl", "E-mail Password"); 44//4, create mail message = CRE Ateattachmail (session); 46//5, Send mail ts.sendmessage (message, message.getallrecipients ()); Ts.clo     Se ();}50/**52 * @Method: createAttachMail53 * @Description: Create a message with an attachment. * @Anthor: Aloof Wolf 55 *56 * @param session57 * @return58 * @throws Exception59 * * public static MimeMessage Createatta Chmail (Session session) throws exception{61 mimemessage message = new MimeMessage (session); 62 63/         /Set basic message 64//Sender Message.setfrom (New InternetAddress ("[email protected]")); 66//Recipient 67 Message.setrecipienT (Message.RecipientType.TO, New InternetAddress ("[email protected]")); 68//Mail Header Message.setsubject ( "JavaMail Mail sending Test"); 70 71//Create message body, in order to avoid the message body Chinese garbled problem, need to use Charset=utf-8 to specify character encoding MimeBodyPart text = new MimeBodyPart (); Text.setcontent ("Mail with attachments created with JavaMail", "Text/html;charset=utf-8"); 74 75//Create a message attachment MimeBodyPart attach = new MimeBodyPart (), DataHandler dh = new DataHandler (New Filedatasource ("src\\2  . jpg "); Attach.setdatahandler (DH); Attach.setfilename (Dh.getname ());         80 81//Create container Description data Relationship Mimemultipart MP = new Mimemultipart (); Mp.addbodypart (text); 84 Mp.addbodypart (attach); Mp.setsubtype ("mixed"); Message.setcontent (MP);          Ssage.savechanges (); 89//writes the created email to the E-disk storage Message.writeto (new FileOutputStream ("e:\\attachmail.eml")); 91 Returns the generated message message;93 return}94} 
3.6. Send complex messages with inline images and attachments
  1 package me.gacl.main;  2 3 Import Java.io.FileOutputStream;  4 Import java.util.Properties;  5 Import Javax.activation.DataHandler;  6 Import Javax.activation.FileDataSource;  7 Import Javax.mail.Message;  8 Import javax.mail.Session; 9 Import Javax.mail.Transport; Ten import javax.mail.internet.InternetAddress; Import Javax.mail.internet.MimeBodyPart; Import Javax.mail.internet.MimeMessage; Import Javax.mail.internet.MimeMultipart; Import javax.mail.internet.MimeUtility;  /** * @ClassName: Sendmail * @Description: Send email * @author: Aloof Wolf * @date: 2015-1-12 9:42:56 21 * 22  * * * public class Sendmail {/** * @param args * @throws Exception * *         static void Main (string[] args) throws Exception {Properties prop = new properties (); 32 Prop.setproperty ("Mail.host", "smtp.sohu.com"); Prop.setproperty ("Mail.transport.protocol", "SMTP"); Prop.setproperty("Mail.smtp.auth", "true"); 35//Use JavaMail to send mail 5 steps 36//1, create session PNS Session session = Session.getinstance (prop); 38//Open session debug mode, so that you can see the program send email running status of Session.setdebug (true); 40//2, through session to get Transport object Transport ts = Session.gettransport (); 42//3, connected to the mail server Ts.connect ("smtp.sohu.com", "GaCl", "email password"); 44//4, create mail message = Createmixedmail (session); 46//5, Send mail ts.sendmessage (message, message.getallrecipients ()); Ts.close (); * @Method: Createmixedmail * @Description: Generate a message with an attachment and a picture/** * @Anthor: Aloof and pale wolf * @param session * @return * @throws Exception * * * mimemessage C Reatemixedmail (Session session) throws Exception {61//Create message MimeMessage message = new MimeMessage (sess ION); 63 64//Set basic information for a message meSsage.setfrom (New InternetAddress ("[email protected]")); Message.setrecipient (Message.RecipientType.TO, New InternetAddress ("[email protected]")); Message.setsubject ("e-mail with attachments and pictures"); 68 69//Text MimeBodyPart text = new MimeBodyPart (); Text.setcontent ("xxx This is female xxxx<br/>

The above is to use the JavaMail API to create the message and send the entire contents of the message.

Javaweb Learning Summary (52)--Create and send messages using JavaMail

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.