Simple implementation of Java mail delivery

Source: Internet
Author: User
Tags auth email account mailmessage

Java Mail is the use of existing mail accounts to send mail tools, for example, I registered an email account in NetEase, through the control of Java mail, I can not personally login NetEase mailbox, let the program automatically use NetEase mailbox to send mail. This mechanism is widely used in such aspects as registration activation and the sending of spam messages.

The general process for sending Java mail is this:

1. Build a concrete class that inherits from Javax.mail.Authenticator, and rewrite the Getpasswordauthentication () method inside. This class is used as a login check to ensure that you have the right to send mail to the mailbox.

2. Build a properties file that contains parameters such as the SMTP server address.

3. Create a javax.mail.Session by building the properties file and Javax.mail.Authenticator concrete class. The session is created in the same way as a login mailbox. The rest of the nature is new mail.

4, the construction of mail content, is generally javax.mail.internet.MimeMessage object, and designated sender, recipient, subject, content and so on.

5. Use the Javax.mail.Transport tool class to send mail.

Here is the specific code:

Method One:

/**
* @ClassName: Authentication
* @Description: Authenticator
* @author: CHENRL
* @date: October 30, 2015 9:59:
*/
public class authentication extends Authenticator {
String username=null;
String Password=null;     

Public authentication () {

}
Public Authentication (string username, string password) {
This.username = Username;
This.password = password;
}
Protected Passwordauthentication getpasswordauthentication () {
Passwordauthentication pa = new Pass Wordauthentication (username, password);
Return PA;
}
}

public class SendMail {
IP and port of the server sending the message
Private String Mailserverhost;
Private String Mailserverport = "25";
Private String fromaddress;
Private String toaddress;
Private String UserName;
private String password;
Private Boolean validate = false;
Private String subject;
Private String content;
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.mailserverport);
P.put ("Mail.smtp.auth", validate?) "True": "false");
return p;
}

Set get

}

public class MailSend {
Public boolean sendtextmail (final SendMail mailinfo) {
Determine if identity authentication is required
Authentication authenticator = NULL;
Properties Pro = Mailinfo.getproperties ();
if (Mailinfo.isvalidate ()) {
If authentication is required, create a password validator
Authenticator = new Authentication (Mailinfo.getusername (), Mailinfo.getpassword ());
}
Constructs a session that sends messages based on mail session properties and password validators
/*session sendmailsession = session.getdefaultinstance (pro,authenticator); */
Session sendmailsession = Session.getdefaultinstance (pro, New Authenticator () {
Protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication (Mailinfo.getusername (), Mailinfo.getpassword ());
}

});
try {
Message MailMessage = new MimeMessage (sendmailsession);
Address from = new InternetAddress (mailinfo.getfromaddress ());
Mailmessage.setfrom (from);
Address to = new InternetAddress (mailinfo.gettoaddress ());
Mailmessage.setrecipient (message.recipienttype.to,to);
Mailmessage.setsubject (Mailinfo.getsubject ());
Mailmessage.setsentdate (New Date ());
String mailcontent = Mailinfo.getcontent ();
Mailmessage.settext (mailcontent);
Transport.send (MailMessage);
return true;
} catch (Messagingexception ex) {
Ex.printstacktrace ();
}
return false;
}
/**
* Send mail in HTML format
*/
public boolean sendhtmlmail (SendMail mailinfo) {
Determine if identity authentication is required
Authentication authenticator = NULL;
Properties Pro = Mailinfo.getproperties ();
if (Mailinfo.isvalidate ()) {
Authenticator = new Authentication (Mailinfo.getusername (), Mailinfo.getpassword ());
}
Constructs a session that sends messages based on mail session properties and password validators
Session sendmailsession = session.getdefaultinstance (pro,authenticator);
try {
Create a mail message based on session
Message MailMessage = new MimeMessage (sendmailsession);
Address from = new InternetAddress (mailinfo.getfromaddress ());
Mailmessage.setfrom (from);
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);
Mailmessage.setsubject (Mailinfo.getsubject ());
Mailmessage.setsentdate (New Date ());
Multipart Mainpart = new Mimemultipart ();
BodyPart html = new MimeBodyPart ();
Html.setcontent (Mailinfo.getcontent (), "text/html; Charset=utf-8 ");
Mainpart.addbodypart (HTML);
Mailmessage.setcontent (Mainpart);
Transport.send (MailMessage);
return true;
} catch (Messagingexception ex) {
Ex.printstacktrace ();
}
return false;
}
}

public class Send {

public static void Main (string[] args) {
Set Message parameters
SendMail mail = new SendMail ();
QQ Mail
Mail.setmailserverhost ("smtp.qq.com"); Here fill in the sender's mailbox server, I use QQ for example
Sina
Mail.setmailserverhost ("smtp.sina.com");
Mail.setmailserverport ("25");
Mail.setvalidate (TRUE);
/*
Mail.setusername ("Sender's mailbox name");
Mail.setpassword ("Sender's email password");
Mail.setfromaddress ("Sender's mailbox name");
Mail.settoaddress ("Recipient's email password");
Mail.setsubject ("title");
Mail.setcontent ("content"); */
/*QQ Mailbox Test Successful */
/*163 Mailbox Test Failed */
/*gov.cn Mailbox Test Failed */
/*sina Mailbox Test Successful */
Send mail
MailSend SMS = new MailSend ();
Sms.sendtextmail (mail);//Send stylistic format
Sms.sendhtmlmail (mail);//Send HTML format
}
}

Method Two: The following method can also be implemented:

/****************************************************************
* For QQ mailbox use (for other use similar you should also change)
* First put the QQ mailbox POP3 SMTP Open
* First determine your network is normal, non-agent
* Make sure that your QQ mailbox has SMTP enabled
* If not turned on, then this setting
* Set-up account--below--Select this [√]smtp to save to the server after sending the letter
****************************************************************/
public class SendEmail {

Setting up the server
private static String key_smtp = "Mail.smtp.host";
private static String value_smtp = "smtp.qq.com";
Server Authentication
private static String Key_props = "Mail.smtp.auth";
private static Boolean value_props = true;
Sender user name, password
Private String Send_user = Emailconfproperties.getemail ();//Your QQ mailbox
Private String Send_uname = Emailconfproperties.getemailname (); Your e-mail name
Private String send_pwd = Emailconfproperties.getemailpwd (); Your e-mail password
Establish a session
Private MimeMessage message;
Private Session S;

/*
* Initialization method
* */
Public SendEmail () {
Properties props = System.getproperties ();
Props.setproperty (KEY_SMTP, VALUE_SMTP);
Props.put (Key_props, value_props);
s = session.getinstance (props);
S.setdebug (TRUE);//debug information after opening
message = new MimeMessage (s);
}

/**
* Send mail
* @param headname message header file name
* @param sendhtml Email content
* @param receiveuser Recipient [email protected]
*/
public void Dosendhtmlemail (String headname,stringbuffer sendhtml,string receiveuser) {
try {
Sender
InternetAddress from = new InternetAddress (send_user);
Message.setfrom (from);
Recipient
InternetAddress to = new InternetAddress (receiveuser);
Message.setrecipient (Message.RecipientType.TO, to);
Message header
Message.setsubject (Headname);
String content = sendhtml.tostring ();
Message content, you can also make plain text "Text/plain"
Message.setcontent (Content, "TEXT/HTML;CHARSET=GBK");
Message.savechanges ();
Transport Transport = S.gettransport ("SMTP");
SMTP authentication is the email user name password you use to send mail
Transport.connect (VALUE_SMTP, Send_uname, send_pwd);
Send
Transport.sendmessage (Message, message.getallrecipients ());
Transport.close ();
} catch (Addressexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Messagingexception e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
Send an email alert
SendEmail email = new SendEmail ();
String server_ip = Emailconfproperties.getserverip ();
String Server_port = Emailconfproperties.getserverport ();
String server_name = Emailconfproperties.getservername ();
String path = "/http" + server_ip + ":" + Server_port + "/" + server_name;
String headname = "User Registration information Audit Notice";
StringBuffer sendhtml = new StringBuffer ("Dear User, Hello:" +
"<br>&nbsp;&nbsp;&nbsp;&nbsp; verification code has been sent to your mailbox, please complete the password recovery function as soon as possible, the verification code is:" + 123 +
"<br>&nbsp;&nbsp;&nbsp;&nbsp; You can: <a href= '" + Path + "' > click here to login </a>" +
"<br><br> system mail, do not reply");
String receiveuser = "[email protected]";
Email.dosendhtmlemail (Headname, sendhtml, Receiveuser);
System.out.println ("Mail has been sent, please pay attention to check!");
}
}

public class Emailconfproperties {
private static properties properties;

static {
Properties = null;
try {
if (properties = = null) {
Properties = new properties ();
Properties.load (EmailConfProperties.class.getClassLoader (). getResourceAsStream ("emailconfig.properties"));
}
} catch (Exception e) {
System.err.println ("not find emailconfig.properties");
E.printstacktrace ();
}
}
Sender Mailbox
public static String Getemail () {
Return Properties.getproperty ("Send_email");
}
Sender Mailbox Name
public static String Getemailname () {
Return Properties.getproperty ("Send_emailname");
}
Sender Mailbox Password
public static String Getemailpwd () {
Return Properties.getproperty ("Send_emailpwd");
}

public static String Getserverip () {
Return Properties.getproperty ("Server_ip");
}
public static String Getserverport () {
Return Properties.getproperty ("Server_port");
}
public static String getServerName () {
return Properties.getproperty ("SERVER_NAME");
}
}

Emailconfig.properties: Configuration file

Send_email = [Email protected]
Send_emailname = 123456789
Send_emailpwd = 123456789
SERVER_IP = 192.168.17.92
Server_port = 8080
server_name = ISMS

Simple implementation of Java mail delivery

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.