General steps for sending an email in java: sending an email in java

Source: Internet
Author: User
Tags server website valid email address email account ssl connection

General steps for sending an email in java: sending an email in java

General steps for sending an email in java

1. Introduce the jar package of javamail:

 

2. Create a test class to write the content of the email to be sent to the computer to check whether the content can be written:

Public static void main (String [] args) throws Exception {// 1. create an email Properties props = new Properties (); // The parameter configuration used to connect to the mail server (used only when sending an email) Session session = Session. getDefaultInstance (props); // create a session object (prepared for sending an email) based on the parameter configuration. MimeMessage message = new MimeMessage (session ); // create an email object/** you can also create a MimeMessage object * MimeMessage message = new MimeMessage (session, new FileInputStream ("MyEmail. eml "));*/ // 2. from: sender // the three parameters of InternetAddress are: Mailbox, And the nickname is displayed (only for display, no special requirements ), the character set encoding of the nickname // The mailbox must be a real and valid email address to be sent. Message. setFrom (new InternetAddress ("123456@qq.com", "USER_AA", "UTF-8"); // 3. to: Recipient message. setRecipient (MimeMessage. recipientType. TO, new InternetAddress ("123654@qq.com", "USER_CC", "UTF-8"); // To: add recipient (optional) // message. addRecipient (MimeMessage. recipientType. TO, new InternetAddress ("dd@receive.com", "USER_DD", "UTF-8"); // Cc: Cc (optional) // message. setRecipient (MimeMessage. recipientType. CC, new InternetAddress ("ee@receive.com", "USER_EE", "UTF-8"); // Bcc (optional) // message. setRecipient (MimeMessage. recipientType. BCC, new InternetAddress ("ff@receive.com", "USER_FF", "UTF-8"); // 4. subject: The mail Subject message. setSubject ("TEST mail subject", "UTF-8"); // 5. content: message Body (html tags can be used. setContent ("TEST: This is the mail body... "," Text/html; charset = UTF-8 "); // 6. set the display sending time message. setSentDate (new Date (); // 7. save the preceding setting message. saveChanges (); // 8. save the email to the local OutputStream out = new FileOutputStream ("D: // MyEmail. eml "); message. writeTo (out); out. flush (); out. close ();}

3. Create an email sending class: send an email to another email account

// Sender's email address and password (replace with your own email address and password) // PS: Some email servers increase the security of their own passwords, set an independent password for the SMTP client (some mailboxes are called "authorization codes"). // for an email with an independent password enabled, this independent password (authorization code) must be used for the password ). Public static String myEmailAccount = "123456@qq.com"; public static String myEmailPassword = "abcdefg"; // The SMTP server address of the sender's mailbox, which must be accurate. Different mail server addresses are different, the general (general, not absolute) format is: smtp.xxx.com // SMTP server address of Netease 163 mailbox: smtp.163.com public static String myEmailSMTPHost = "smtp.qq.com "; // recipient mailbox (Replace with the valid mailbox you know) public static String receiveMailAccount = "123654@qq.com"; public static void main (String [] args) throws Ex Ception {// 1. create a parameter configuration for connecting to the mail server. The parameter configuration Properties props = new Properties (); // The parameter configuration props. setProperty ("mail. transport. protocol "," smtp "); // The protocol used (JavaMail specification requirements) props. setProperty ("mail. smtp. host ", myEmailSMTPHost); // The SMTP server address of the sender's email address props. setProperty ("mail. smtp. auth "," true "); // authentication requests required // PS: Some mailbox servers require SSL authentication for SMTP connections. (to improve security, the mailbox supports SSL connections, you can also enable it on your own). // if you cannot connect to the mail server, check the log printed on the console carefully. "Connection failed, SSL secure connection required" and other errors, // open the annotation code between the following/*... */and enable the SSL secure connection. /* // SMTP server port (the default port for non-SSL connection is 25, which can be left empty. If the SSL connection is enabled, // you need to change the port of the SMTP server of the corresponding mailbox. For details, see the help of the corresponding mailbox service. // The SMTP (SLL) Port of the QQ mailbox is 465 or 587, check other mailboxes by yourself) final String smtpPort = "465"; props. setProperty ("mail. smtp. port ", smtpPort); props. setProperty ("mail. smtp. socketFactory. class "," javax.net. ssl. SSLSocketFactory "); props. setProperty ("mail. smtp. socketFactory. fallback "," false "); props. setProperty ("mail. smtp. SocketFactory. port ", smtpPort); * // 2. create a Session Object Based on the configuration, used to interact with the mail server session = Session. getDefaultInstance (props); session. setDebug (true); // set it to debug mode. You can view the detailed sending log // 3. create an email MimeMessage message = createMimeMessage (session, myEmailAccount, receiveMailAccount); // 4. obtain the email transmission object Transport transport = Session based on the session. getTransport (); // 5. use the email account and password to connect to the email server. The authenticated email address must be the same as the sender email address in the message. No Then an error is reported /// PS_01: the Key to Success or failure determination is this sentence. If the connection to the server fails, logs of the corresponding failure cause will be output on the console. // check the failure cause carefully, some email servers will return error codes or view links of error types, and view the specific failure cause on the help website of the corresponding email server based on the error // type. /// PS_02: the cause of connection failure is usually the following. Check the code carefully: // (1) the SMTP service is not enabled on the mailbox; // (2) the mailbox password is incorrect, for example, an independent password is enabled for some mailboxes; // (3) the mailbox server requires that SSL connections be used; // (4) requests are too frequent or for other reasons, rejected by the email server; // (5) if the above points are correct, go to the email server website to find help. /// PS_03: Check the log carefully, read the log carefully, and understand the log. The error causes are described in the log. Transport. connect (myEmailAccount, myEmailPassword); // 6. send an email to all recipient addresses, such as message. getAllRecipients () obtains all recipients, CC recipients, and BCC transport added when the email object is created. sendMessage (message, message. getAllRecipients (); // 7. disable the connection to transport. close ();}

4. Define a method for creating a text content Email:

Public static MimeMessage createMimeMessage (Session session, String sendMail, String receiveMail) throws Exception {// 1. create an email MimeMessage message = new MimeMessage (session); // 2. from: The sender (the nickname is suspected of being an advertisement. Avoid being mistaken by the email server for an advertisement or returning failure. Modify the nickname) message. setFrom (new InternetAddress (sendMail, "sss", "UTF-8"); // 3. to: recipient (multiple recipients, CC, and BCC can be added) message. setRecipient (MimeMessage. recipientType. TO, new InternetAddress (rec EiveMail, "zzz", "UTF-8"); // 4. subject: The Subject of the email (the title is suspected of being an advertisement, so as to avoid being mistaken by the email server for advertising or returning failure. Please modify the title) message. setSubject ("meeting notification", "UTF-8"); // 5. content: The body of the email (html tags can be used) (the Content is suspected of being advertisement, so as to avoid being mistaken by the email server for sending advertisements or returning failures. Please modify the Content to be sent) message. setContent ("the meeting room will be held at three o'clock P.M. today. "," Text/html; charset = UTF-8 "); // 6. set the sending time message. setSentDate (new Date (); // 7. save the Set message. saveChanges (); return message ;}

5. You can send emails through personal experience. Note the following:

The SMTP client must be activated in the mail sender's mailbox. If the sender's mailbox is not activated, it cannot be sent successfully.

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.