JavaMail instance code sharing for sending mail _java

Source: Internet
Author: User
Tags mailmessage
Note: To import the JavaMail Mail.jar package first
The following three pieces of code are all my code, friends if you want to use, direct replication can be.
First Class: Mailsenderinfo.java
Copy Code code as follows:

Package com.util.mail;
Import java.util.Properties;
/**
* Basic information to be used for sending mail
*/
public class Mailsenderinfo {
IP and port of the server that sent the message
Private String Mailserverhost;
Private String Mailserverport = "25";
Address of the sender of the message
Private String fromaddress;
Address of the Mail recipient
Private String toaddress;
User name and password for the log on mail sending server
Private String UserName;
private String password;
Whether authentication is required
Private Boolean validate = false;
Message subject
Private String subject;
Text content of a message
Private String content;
File name of the message attachment
Private string[] attachfilenames;
/**
* Get mail Session properties
*/
Public Properties getProperties () {
Properties P = new properties ();
P.put ("Mail.smtp.host", this.mailserverhost);
P.put ("Mail.smtp.port", this.mailserverhost);
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[] attachfilenames) {
This.attachfilenames = Attachfilenames;
}
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 content) {
this.content = content;
}
}

Second class: Simplemailsender.java
Copy Code code as follows:

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.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMultipart;
/**
* Simple Mail (without attachment) transmitter
*/
public class Simplemailsender {
/**
* Send mail in text format
* @param mailinfo messages to be sent
*/
public boolean sendtextmail (Mailsenderinfo mailinfo) {
To determine whether an identity certificate is required
Myauthenticator authenticator = null;
Properties Pro = Mailinfo.getproperties ();
if (Mailinfo.isvalidate ()) {
If authentication is required, create a password validator
Authenticator = new Myauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());
}
Constructs a session that sends a message based on the message conversation properties and the password validator
Session sendmailsession = Session.getdefaultinstance (pro, authenticator);
try {
Create a mail message based on session
Message MailMessage = new MimeMessage (sendmailsession);
Create Mail Sender Address
Address from = new InternetAddress (mailinfo.getfromaddress ());
Set the sender of a mail message
Mailmessage.setfrom (from);
Create the recipient address of the message and set it to the mail message
Address to = new InternetAddress (mailinfo.gettoaddress ());
The Message.RecipientType.TO property indicates that the recipient's type is to
Mailmessage.setrecipient (Message.RecipientType.TO, to);
Set the subject of a mail message
Mailmessage.setsubject (Mailinfo.getsubject ());
Set when mail messages are sent
Mailmessage.setsentdate (New Date ());
Set the main contents of a mail message
String mailcontent = Mailinfo.getcontent ();
Mailmessage.settext (mailcontent);
Send mail
Transport.send (MailMessage);
return true;
catch (Addressexception e) {
E.printstacktrace ();
catch (Messagingexception e) {
E.printstacktrace ();
}
return false;
}
/**
* Send mail in HTML format
* @param mailinfo messages to be sent
*/
public boolean sendhtmlmail (Mailsenderinfo mailinfo) {
To determine whether an identity certificate is required
Myauthenticator authenticator = null;
Properties Pro = Mailinfo.getproperties ();
if (Mailinfo.isvalidate ()) {
If authentication is required, create a password validator
Authenticator = new Myauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());
}
Constructs a session that sends a message based on the message conversation properties and the password validator
Session sendmailsession = Session.getdefaultinstance (pro, authenticator);
try {
Create a mail message based on session
Message MailMessage = new MimeMessage (sendmailsession);
Create Mail Sender Address
Address from = new InternetAddress (mailinfo.getfromaddress ());
Set the sender of a mail message
Mailmessage.setfrom (from);
Create the recipient address of the message and set it to the mail message
Address to = new InternetAddress (mailinfo.gettoaddress ());
The Message.RecipientType.TO property indicates that the recipient's type is to
Mailmessage.setrecipient (Message.RecipientType.TO, to);
Set the subject of a mail message
Mailmessage.setsubject (Mailinfo.getsubject ());
Set when mail messages are sent
Mailmessage.setsentdate (New Date ());
The Mimemultipart class is a container class that contains objects of type MimeBodyPart
Multipart Mainpart = new Mimemultipart ();
Create a mimebodypart that contains HTML content
BodyPart html = new MimeBodyPart ();
Set HTML content
Html.setcontent (Mailinfo.getcontent (), "text/html; Charset=utf-8 ");
Mainpart.addbodypart (HTML);
Set the Mainpart object as the message content
Mailmessage.setcontent (Mainpart);
Send mail
Transport.send (MailMessage);
return true;
catch (Addressexception e) {
E.printstacktrace ();
catch (Messagingexception e) {
E.printstacktrace ();
}
return false;
}
}

Third class: Myauthenticator.java
Copy Code code as follows:

Package com.util.mail;
Import javax.mail.*;
/**
* Identity Certification
*/
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;
}
@Override
Protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication (userName, password);
}
}

Here is a code that uses the above three classes:
Copy Code code as follows:

Package com.util.mail;
/**
* Send mail
*/
public class Mail {
/**
* @param args
*/
public static void Main (string[] args) {
This class is primarily about setting up messages
Mailsenderinfo mailinfo = new Mailsenderinfo ();
Mailinfo.setmailserverhost ("smtp.126.com");
Mailinfo.setmailserverport ("25");
Mailinfo.setvalidate (TRUE);
Mailinfo.setusername ("test@126.com");
Mailinfo.setpassword ("test");
Mailinfo.setfromaddress ("test@126.com");
Mailinfo.settoaddress ("test@qq.com");
Mailinfo.setsubject ("Set mailbox title such as http://www.guihua.org Chinese sweet-scented osmanthus net");
Mailinfo.setcontent ("Set up mailbox content such as http://www.guihua.org Chinese sweet-scented osmanthus NET is China's largest sweet Osmanthus website = =");
This class is primarily to send mail
Simplemailsender SMS = new Simplemailsender ();
Sms.sendtextmail (Mailinfo);
Sms.sendhtmlmail (Mailinfo);
}
}

Finally, give friends a few attention to the place:
1, the use of this code you can complete your JavaMail mail delivery function. Three classes are indispensable.
2, these three classes I pack is used Com.util.mail package, if not like, you can change, but three class files must be in the same package
3, do not use the mailbox you have just registered in the program to send e-mail, if your 163 mailbox is just registered soon, then you do not use the "smtp.163.com". Because you can't send out. Just registered mailbox will not give you this permission, that is, you can not pass the verification. Use the mailbox you use frequently, and the time is long.
4. Another problem is mailinfo.setmailserverhost ("smtp.163.com") and Mailinfo.setfromaddress ("han2000lei@163.com"); That is, if you use a 163SMTP server, the e-mail address must be sent to 163 of the mailbox, if not, it will not be sent successfully.
5, on the issue of JavaMail validation errors, there are many explanations on the web, but I see only one. That's my third class. All you have to do is copy the code, and I don't think it's going to be a problem.

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.