The previous article describes the manual implementation of their own to send ordinary email, HTML type of email and email with attachments. In fact, the Apache Commons project has an email sub-project, it is JavaMail API encapsulation, used to be very convenient. Here's a quick introduction.
1. First configure the required jar package
Mail.jar and Commons-email.jar need to be added to our classpath, such as:
2. Send regular mail
/** * Send regular mail with org.apache.commons.mail * * @author Wangzhipeng * */public class Testcommon {public Testcommon () {}p Ublic static void Main (string[] args) {simpleemail email = new Simpleemail (); Email.sethostname ("smtp.qq.com");// Set up a mail server using email, here is a QQ mailbox for example (other example: "Smtp.163.com", "smtp.sohu.com") try {//Recipient mailbox Email.addto ("[email protected]");// Mailbox Server Authentication Email.setauthentication ("Your email address", "your email password"),//Sender's mailbox Email.setfrom ("Your email address");//Message subject Email.setsubject (" Zhipeng-javamail ");//Mail Content email.setmsg (" Kobe Bryante never Stop Trying ");//Send mail Email.send ();} catch (Emailexception ex) {ex.printstacktrace ();}}}
3. Sending HTML type messages
/** * Send HTML mail with Org.apache.commons.mail * * @author Wangzhipeng * */public class Testcommonhtml {public Testcommonhtml () {}public static void main (string[] args) {//Do not use Simpleemail, there will be garbled problems htmlemail email = new Htmlemail ();// Simpleemail email = new Simpleemail (); try {//Here is the name of the SMTP sending server: QQ is as follows: Email.sethostname ("smtp.qq.com");// The setting of the character encoding set Email.setcharset ("GBK"),//The recipient's mailbox Email.addto ("Your email address"),//Sender's mailbox Email.setfrom ("[Email protected]", " Wangzhipeng ")//If authentication information is required, set authentication: username-password. Email.setauthentication ("Your email address", "your email password") for the sender's registered name and password on the mail server, Email.setsubject ("3:00 meeting room discussion, please attend on time");//information to be sent , due to the use of htmlemail, you can use HTML tags in the message content email.setmsg ("
The results are as follows:
Java Send email-using Org.apache.commons.mail