The process of implementing Java to send mail is generally the following steps:
- Prepare a properties file that holds parameters such as the SMTP server address.
- Create a Session object with properties
- Create a Message object with session and set the subject and body
- Send mail with Transport object
There are 2 jars required: Activation.jar and Mail.jar
See a demo code directly
#----------------These are the fields necessary to build the session----------
#smtp服务器
Mail.smtp.host=smtp.qq.com
#身份验证
Mail.smtp.auth=true
#--------------------------------------------------------------
#发送者的邮箱用户名
[Email protected]
#发送者的邮箱密码
Mail.sender.password=xxxxxxxxxx
Mailserver.properties
Here is the Java code to send the message
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import javax.mail.internet.MimeUtility;
public class JavaMail {
/**
* Message object will store the e-mail messages we actually send,
* The message object is created as a MimeMessage object and needs to know which JavaMail session should be selected.
*/
Private mimemessage message;
The
/**
* Session class represents a mail session in JavaMail.
* Each JavaMail-based application has at least one session (can have any number of sessions).
*
* JavaMail requires properties to create a Session object.
* Search for "Mail.smtp.host" attribute value is the host sending the message
* looking for "Mail.smtp.auth" authentication, the current free mail server requires this
*/
Private session session;
/***
* Messages can be either sent or received. JavaMail uses two different classes to accomplish these two functions: Transport and Store. The
* Transport is used to send messages, and the store is used to receive letters. For this tutorial we only need to use the transport object.
*/
Private Transport Transport;
Private String mailhost= "";
Private String sender_username= "";
Private String sender_password= "";
Private Properties Properties = new properties ();
/*
* Initialization method
*/
Public JavaMail (Boolean debug) {
InputStream in = JavaMail.class.getResourceAsStream ("mailserver.properties");
try {
Properties.load (in);
This.mailhost = Properties.getproperty ("Mail.smtp.host");
This.sender_username = Properties.getproperty ("Mail.sender.username");
This.sender_password = Properties.getproperty ("Mail.sender.password");
} catch (IOException e) {
E.printstacktrace ();
}
Session = Session.getinstance (properties);
Session.setdebug (debug);//debug information after opening
message = new MimeMessage (session);
}
/**
* Send mail
*
* @param subject
* Email Subject
* @param sendhtml
* Email Content
* @param receiveuser
* Recipient Address
*/
public void Dosendhtmlemail (string subject, String sendhtml,
String Receiveuser) {
try {
Sender
InternetAddress from = new InternetAddress (sender_username);
The following is the setting of the sender's nick name
InternetAddress from = new InternetAddress (Mimeutility.encodeword ("phantom") + "<" +sender_username+ ">");
Message.setfrom (from);
Recipient
InternetAddress to = new InternetAddress (receiveuser);
Message.setrecipient (Message.RecipientType.TO, to);//can also have CC, BCC
Message subject
Message.setsubject (subject);
String content = sendhtml.tostring ();
Message content, you can also make plain text "Text/plain"
Message.setcontent (Content, "text/html;charset=utf-8");
Save Message
Message.savechanges ();
Transport = Session.gettransport ("SMTP");
SMTP authentication is the email user name password you use to send mail
Transport.connect (MailHost, Sender_username, Sender_password);
Send
Transport.sendmessage (Message, message.getallrecipients ());
System.out.println ("Send success!");
} catch (Exception e) {
E.printstacktrace ();
}finally {
if (transport!=null) {
try {
Transport.close ();
} catch (Messagingexception e) {
E.printstacktrace ();
}
}
}
}
public static void Main (string[] args) {
JavaMail se = new JavaMail (false);
Se.dosendhtmlemail ("Mail Subject", "Mail Content", "[email protected]");
}
}
Only the text can be sent above, if we want to send an attachment, we need to use the multipart object.
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;
Import Javax.activation.DataHandler;
Import Javax.activation.DataSource;
Import Javax.activation.FileDataSource;
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;
Import javax.mail.internet.MimeUtility;
public class Javamailwithattachment {
Private MimeMessage message;
Private session session;
Private Transport Transport;
Private String MailHost = "";
Private String Sender_username = "";
Private String Sender_password = "";
Private Properties Properties = new properties ();
/*
* Initialization method
*/
Public Javamailwithattachment (Boolean debug) {
InputStream in = JavaMailWithAttachment.class.getResourceAsStream ("mailserver.properties");
try {
Properties.load (in);
This.mailhost = Properties.getproperty ("Mail.smtp.host");
This.sender_username = Properties.getproperty ("Mail.sender.username");
This.sender_password = Properties.getproperty ("Mail.sender.password");
} catch (IOException e) {
E.printstacktrace ();
}
Session = Session.getinstance (properties);
Session.setdebug (debug);//debug information after opening
message = new MimeMessage (session);
}
/**
* Send mail
*
* @param subject
* Email Subject
* @param sendhtml
* Email Content
* @param receiveuser
* Recipient Address
* @param attachment
* Accessories
*/
public void Dosendhtmlemail (string subject, String sendhtml, String receiveuser, File attachment) {
try {
Sender
InternetAddress from = new InternetAddress (sender_username);
Message.setfrom (from);
Recipient
InternetAddress to = new InternetAddress (receiveuser);
Message.setrecipient (Message.RecipientType.TO, to);
Message subject
Message.setsubject (subject);
Add various parts of the message to the multipart object, including text content and attachments
Multipart Multipart = new Mimemultipart ();
Add Message body
BodyPart Contentpart = new MimeBodyPart ();
Contentpart.setcontent (sendhtml, "text/html;charset=utf-8");
Multipart.addbodypart (Contentpart);
Add the contents of an attachment
if (attachment! = NULL) {
BodyPart Attachmentbodypart = new MimeBodyPart ();
DataSource Source = new Filedatasource (attachment);
Attachmentbodypart.setdatahandler (new DataHandler (source));
Online spread of the solution file name garbled method, in fact, with Mimeutility.encodeword can be very convenient to fix
It is important to use the following BASE64 encoded conversion to ensure that your Chinese attachment header name is not garbled when it is sent
Sun.misc.BASE64Encoder enc = new Sun.misc.BASE64Encoder ();
Messagebodypart.setfilename ("=? GBK? B? "+ Enc.encode (Attachment.getname (). GetBytes ()) +"? = ");
Mimeutility.encodeword can avoid garbled file names
Attachmentbodypart.setfilename (Mimeutility.encodeword (Attachment.getname ()));
Multipart.addbodypart (Attachmentbodypart);
}
Place the multipart object in the message
Message.setcontent (multipart);
Save Message
Message.savechanges ();
Transport = Session.gettransport ("SMTP");
SMTP authentication is the email user name password you use to send mail
Transport.connect (MailHost, Sender_username, Sender_password);
Send
Transport.sendmessage (Message, message.getallrecipients ());
System.out.println ("Send success!");
} catch (Exception e) {
E.printstacktrace ();
} finally {
if (transport! = null) {
try {
Transport.close ();
} catch (Messagingexception e) {
E.printstacktrace ();
}
}
}
}
public static void Main (string[] args) {
Javamailwithattachment se = new javamailwithattachment (true);
File affix = new file ("c:\\ test-test.txt");
Se.dosendhtmlemail ("Mail Subject", "Mail Content", "[email protected]", affix);//
}
}
With accessories
Java send mail (with attachments)