Send an email to JavaMail

Source: Internet
Author: User
Tags mailmessage

Today, I learned about JavaMail. It is really troublesome to send an email to javamail. The core classes used to process emails in the JavaMail package are Session, Message, Address, Authenticator, Transport, Store, and Folder. Session defines a basic mail Session, which needs to read information similar to the mail server, user name, and password from Properties. In addition, the JavaMail API frameworks include James and Spring Mail.
For future convenience, I wrote some code and made it into a jar package to facilitate future use.
The following three pieces of code are all my codes. If you want to use them, copy them directly.
My code has three classes:
First Class: MailSenderInfo. java
[Java]
Package com. util. mail;
/**
* Basic information required for sending emails
*/
Import java. util. Properties;
Public class MailSenderInfo {
// IP address and port of the server sending the mail
Private String mailServerHost;
Private String mailServerPort = "25 ";
// The sender's address
Private String fromAddress;
// Email recipient's address
Private String toAddress;
// Log on to the email sending server's username and password
Private String userName;
Private String password;
// Whether authentication is required
Private boolean validate = false;
// Email Subject
Private String subject;
// Text of the email
Private String content;
// File Name of the email attachment
Private String [] attachFileNames;
/**
* Get mail session attributes
*/
Public Properties getProperties (){
Properties p = new Properties ();
P. put ("mail. smtp. host", this. mailServerHost );
P. put ("mail. smtp. port", this. mailServerPort );
P. put ("mail. smtp. auth", validate? "True": "false ");
Return p;
}
Public String getMailServerHost (){
Return mailServerHost;
}
Public void setMailServerHost (String mailServerHost ){
This. mailServerHost = mailServerHost;
}
Public String getMailServerPort (){
Return mailServerPort;
}
Public void setMailServerPort (String mailServerPort ){
This. mailServerPort = mailServerPort;
}
Public boolean isValidate (){
Return validate;
}
Public void setValidate (boolean validate ){
This. validate = validate;
}
Public String [] getAttachFileNames (){
Return attachFileNames;
}
Public void setAttachFileNames (String [] fileNames ){
This. attachFileNames = fileNames;
}
Public String getFromAddress (){
Return fromAddress;
}
Public void setFromAddress (String fromAddress ){
This. fromAddress = fromAddress;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
Public String getToAddress (){
Return toAddress;
}
Public void setToAddress (String toAddress ){
This. toAddress = toAddress;
}
Public String getUserName (){
Return userName;
}
Public void setUserName (String userName ){
This. userName = userName;
}
Public String getSubject (){
Return subject;
}
Public void setSubject (String subject ){
This. subject = subject;
}
Public String getContent (){
Return content;
}
Public void setContent (String textContent ){
This. content = textContent;
}
}
Second Class: SimpleMailSender. java
[Java]
Package com. util. mail;
 
Import java. util. Date;
Import java. util. Properties;
Import javax. mail. Address;
Import javax. mail. BodyPart;
Import javax. mail. Message;
Import javax. mail. MessagingException;
Import javax. mail. Multipart;
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;
 
/**
* Simple email (email without attachments) sender
*/
Public class SimpleMailSender {
/**
* Send emails in text format
* @ Param mailInfo information of the email to be sent
*/
Public boolean sendTextMail (MailSenderInfo mailInfo ){
// Determine whether identity authentication is required
MyAuthenticator authenticator = null;
Properties pro = mailInfo. getProperties ();
If (mailInfo. isValidate ()){
// If You Need identity authentication, create a password authenticator
Authenticator = new MyAuthenticator (mailInfo. getUserName (), mailInfo. getPassword ());
}
// Construct a mail sending session based on the mail session attribute and the password validator
Session sendMailSession = Session. getDefaultInstance (pro, authenticator );
Try {
// Create an email message based on the session
Message mailMessage = new MimeMessage (sendMailSession );
// Create the mail sender address
Address from = new InternetAddress (mailInfo. getFromAddress ());
// Set the sender of the email message
MailMessage. setFrom (from );
// Create the email receiver address and set it to the email message
Address to = new InternetAddress (mailInfo. getToAddress ());
MailMessage. setRecipient (Message. RecipientType. TO, );
// Set the subject of the email message
MailMessage. setSubject (mailInfo. getSubject ());
// Set the mail message sending time
MailMessage. setSentDate (new Date ());
// Set the main content of the email message
String mailContent = mailInfo. getContent ();
MailMessage. setText (mailContent );
// Send an email
Transport. send (mailMessage );
Return true;
} Catch (MessagingException ex ){
Ex. printStackTrace ();
}
Return false;
}

/**
* Send emails in HTML Format
* @ Param mailInfo refers to the mail information to be sent.
*/
Public static boolean sendHtmlMail (MailSenderInfo mailInfo ){
// Determine whether identity authentication is required
MyAuthenticator authenticator = null;
Properties pro = mailInfo. getProperties ();
// If You Need identity authentication, create a password authenticator
If (mailInfo. isValidate ()){
Authenticator = new MyAuthenticator (mailInfo. getUserName (), mailInfo. getPassword ());
}
// Construct a mail sending session based on the mail session attribute and the password validator
Session sendMailSession = Session. getDefaultInstance (pro, authenticator );
Try {
// Create an email message based on the session
Message mailMessage = new MimeMessage (sendMailSession );
// Create the mail sender address
Address from = new InternetAddress (mailInfo. getFromAddress ());
// Set the sender of the email message
MailMessage. setFrom (from );
// Create the email receiver address and set it to the email message
Address to = new InternetAddress (mailInfo. getToAddress ());
// The Message. RecipientType. TO attribute indicates that the type of the recipient is
MailMessage. setRecipient (Message. RecipientType. TO, );
// Set the subject of the email message
MailMessage. setSubject (mailInfo. getSubject ());
// Set the mail message sending time
MailMessage. setSentDate (new Date ());
// The MiniMultipart class is a container class that contains objects of the MimeBodyPart type.
Multipart mainPart = new MimeMultipart ();
// Create a MimeBodyPart containing HTML content
BodyPart html = new MimeBodyPart ();
// Set HTML content
Html. setContent (mailInfo. getContent (), "text/html; charset = UTF-8 ");
MainPart. addBodyPart (html );
// Set the MiniMultipart object to the Mail content
MailMessage. setContent (mainPart );
// Send an email
Transport. send (mailMessage );
Return true;
} Catch (MessagingException ex ){
Ex. printStackTrace ();
}
Return false;
}
}
Third class: MyAuthenticator. java
[Java]
Package com. util. mail;
 
Import javax. mail .*;

Public class MyAuthenticator extends Authenticator {
String userName = null;
String password = null;

Public MyAuthenticator (){
}
Public MyAuthenticator (String username, String password ){
This. userName = username;
This. password = password;
}
Protected PasswordAuthentication getPasswordAuthentication (){
Return new PasswordAuthentication (userName, password );
}
}
The following code uses the above three classes:
[Java]
Public static void main (String [] args ){
// This class is mainly used to set emails
MailSenderInfo mailInfo = new MailSenderInfo ();
MailInfo. setMailServerHost ("smtp.163.com ");
MailInfo. setMailServerPort ("25 ");
MailInfo. setValidate (true );
MailInfo. setUserName ("han2000lei@163.com ");
MailInfo. setPassword ("***********"); // your email password
MailInfo. setFromAddress ("han2000lei@163.com ");
MailInfo. setToAddress ("han2000lei@163.com ");
MailInfo. setSubject ("set email title ");
MailInfo. setContent ("set email content ");
// This class mainly sends emails
SimpleMailSender sms = new SimpleMailSender ();
Sms. sendTextMail (mailInfo); // sending Style
Sms. sendHtmlMail (mailInfo); // sends the message in html format.
}
Finally, I will give my friends some notes:
1. You can use this code to complete the javamail mail sending function. Three categories are indispensable.
2. I package the com. util. mail package for these three classes. If you do not like the package, you can change it by yourself, but the three class files must be in the same package.
3. Do not use the email address you just registered to send emails in the program. If your 163 email address is just registered, do not use "smtp.163.com ". Because you cannot send it out. The newly registered email address does not give you such permissions, that is, you cannot pass verification. It takes a long time to use your frequently used email address.
4. Another problem is mailInfo. setMailServerHost ("smtp.163.com"); and mailInfo. setFromAddress ("han2000lei@163.com. That is, if you use the 163smtp server, you must use the 163 email address to send the email. If you do not use the email address, the email will not be sent successfully.
5. There are many online explanations about javamail verification errors, but I only see one. Is my third class. As long as you copy all the code, I think there will be no problem.
Author: wangpen#47

Related Article

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.