Java Mailbox Send Tool class

Source: Internet
Author: User
Tags mailmessage stringbuffer
Package com.zhensheng.keji.common.utils;


Import java.io.UnsupportedEncodingException;
Import Java.util.Date;
Import java.util.Properties;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;


Import Javax.activation.DataHandler;
Import Javax.activation.FileDataSource;
Import javax.mail.Address;
Import Javax.mail.Authenticator;
Import Javax.mail.BodyPart;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
Import javax.mail.PasswordAuthentication;
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;


Import Com.zhensheng.keji.common.config.Global;


/**
* Util class for sending mail
*
*/
public class Emailutil {


/**
* Send mail
*
* Information for outgoing messages
*/
public Boolean sendMail () {
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
String tolist = null;
String Tolistcs = null;
String TOLISTMS = null;


if (mailinfo.gettoaddress ()!= null) {
ToList = Getmaillist (Mailinfo.gettoaddress ());
internetaddress[] iatolist = new InternetAddress (). Parse (ToList);
Mailmessage.setrecipients (Message.RecipientType.TO, iatolist); Recipient
}
if (mailinfo.getcsaddress ()!= null) {
Tolistcs = Getmaillist (Mailinfo.getcsaddress ());
internetaddress[] iacslist = new InternetAddress (). Parse (TOLISTCS);
Mailmessage.setrecipients (Message.RecipientType.CC, iacslist); Recipient
}
Secret Send
if (mailinfo.getmsaddress ()!= null) {
Tolistms = Getmaillist (Mailinfo.getmsaddress ());
internetaddress[] Iatolistms = new InternetAddress (). Parse (TOLISTMS);
Mailmessage.setrecipients (Message.RecipientType.BCC, IATOLISTMS); The secret to send people
}
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
Mailmessage.settext (Mailinfo.getcontent ());
The Minimultipart class is a container class that contains objects of type MimeBodyPart
Multipart Multipart = new Mimemultipart ();
Create a mimebodypart that contains HTML content
BodyPart Messagebodypart = new MimeBodyPart ();
Display text content in HTML format
Messagebodypart.setcontent (Mailinfo.getcontent (), "TEXT/HTML;CHARSET=GBK");
Multipart.addbodypart (Messagebodypart);
2. Save multiple attachments
if (mailinfo.getattachfilenames ()!= null) {
Addtach (Mailinfo.getattachfilenames (), multipart);
}
Mailmessage.setcontent (multipart);
Send mail
Transport.send (MailMessage, mailmessage.getallrecipients ());
return true;
catch (Messagingexception ex) {
Ex.printstacktrace ();
catch (Unsupportedencodingexception e) {
E.printstacktrace ();
}
return false;
}


Add multiple Attachments
public void Addtach (String filelist[], Multipart Multipart)
Throws Messagingexception, Unsupportedencodingexception {
for (int index = 0; index < filelist.length; index++) {
MimeBodyPart Mailarchieve = new MimeBodyPart ();
Filedatasource FDS = new Filedatasource (Filelist[index]);
Mailarchieve.setdatahandler (New DataHandler (FDS));
Mailarchieve.setfilename (Mimeutility.encodetext (Fds.getname (), "GBK", "B"));
Multipart.addbodypart (Mailarchieve);
}
}


Private String getmaillist (string[] mailarray) {


StringBuffer tolist = new StringBuffer ();
int length = Mailarray.length;
if (Mailarray!= null && length < 2) {
Tolist.append (Mailarray[0]);
} else {
for (int i = 0; i < length; i++) {
Tolist.append (Mailarray[i]);
if (I!= (length-1)) {
Tolist.append (",");
}


}
}
return tolist.tostring ();


}


/**
*
* @param mailserverhost
* Mail Server domain name
* @param mailserverport
* Mail server address
* @param userName
* User Name
* @param password
* Password
* @param toaddress
* Mailing Address
* @param subject
* Message Subject
* @param content
* Message Content
*/
Public Emailutil (String mailserverhost, String mailserverport, String userName, string password, string[] toaddress,
String[] csaddress, String msaddress[], string subject, string content, string[] attachments) {
This.mailInfo.setMailServerHost (Mailserverhost);
This.mailInfo.setMailServerPort (Mailserverport);
This.mailInfo.setValidate (TRUE);
This.mailInfo.setUserName (UserName);
This.mailInfo.setPassword (password);
This.mailInfo.setFromAddress (UserName);
This.mailInfo.setToAddress (toaddress);
This.mailInfo.setCsAddress (csaddress);
This.mailInfo.setMsAddress (msaddress);
This.mailInfo.setSubject (subject);
This.mailInfo.setContent (content);
This.mailInfo.setAttachFileNames (attachments);
}


Private Mailsenderinfo Mailinfo = new Mailsenderinfo ();


Public Mailsenderinfo Getmailinfo () {
return mailinfo;
}


public void Setmailinfo (Mailsenderinfo mailinfo) {
This.mailinfo = Mailinfo;
}


Public boolean isemail (final String searchphrase) {
Final String check = "^" ([a-z0-9a-z]+[-|\\.]?) +[a-z0-9a-z]@ ([a-z0-9a-z]+ (-[a-z0-9a-z]+)/\.) +[a-za-z]{2,}$ ";
Final pattern regex = pattern.compile (check);
Final Matcher Matcher = Regex.matcher (searchphrase);
return matcher.matches ();
}


public static string Getverifymail (string userId, string email, string verifycode) {


String content = "<div class=\" main_cen\ ">\n\n" + "<p class=\" Title_all zi_6\ ">\n" + "Thank you for registering your membership!<br>\n"
+ "Your login account is: <span class=\" title_big2\ "><a target=\" _blank\ "href=\" mailto: "+ email +" > "+ Email
+ "</a> </span>\n" + "</p>\n\n" +


"<p class=\" Title_all_top zi_6 link\ "+" to enable the account and confirm the e-mail address, click the following link: >\n "+


"<a target=\" _blank\ "href=\" http://www.uxiaoqu.com/register/signup.action?v= "+ Verifycode +" &userid= "
+ userId + "\ >http://www.uxiaoqu.com/register/signup.action?v=" + Verifycode + "&userid=" + userId
+ "</a><br>\n" + "<span class=\" red\ "> (please complete the confirmation within 48 hours, 48 hours after the message is invalid, you will need to fill in the registration information) </span>\n" + "< /p>\n\n "+


"<p class=\" Title_all_top zi_6\ ">" If you cannot access it by clicking the above link, copy and paste the URL into a new browser window. <br> \ n "
+ "If you have received this email incorrectly, you do not need to do anything to cancel the account." This account will not start. \ n "+" </p>\n\n "
// +
"<p class=\" Title_all_top zi_6 link\ ">\n\n"
// +


"If you have any questions or questions about your account, please visit Sina Member Registration FAQ, address is as follows: <br>\n"
// +
"<a target=\" _blank\ "
Href=\ "Http://iask.sina.com.cn/browse/get_class4.php?fatherid=1315&amp;nav=1\" >http:// Iask.sina.com.cn/browse/get_class4.php?fatherid=1315&amp;nav=1
</a><br> "
+ "This is just an announcement mail." We do not monitor or answer responses to this message. \ n "+" </p>\n\n "+


"</div>\n";


return content;
}


public static void Main (string[] args) {
String mailserverhost = "smtp.exmail.qq.com";
String mailserverport = "25";
String userName = "service@raylinetech.com";
String password = "WLlrXJC83";
String[] toaddress = {"274047154@qq.com"};
String cs[] = {"15522500416@163.com"};
String ms[] = null;
String subject = "is inside." ";
string[] arrarchievlist = null;
//
String content = "letter." <a href=\ "http://login.sina.com.cn/signup/signupmail2.php?r=d8d75c579625472cf70196914e7fbebd\" >http:// Login.sina.com.cn/signup/signupmail2.php?r=d8d75c579625472cf70196914e7fbebd</a> ";
Emailutil util = new Emailutil (Mailserverhost, Mailserverport,
UserName, password, toaddress, CS, MS, subject,
Content, arrarchievlist);
System.out.println (Util.sendmail ());
System.out.println (Emailutil.getverifymail ("123", "1234"));


Emailutil.sendemail ("18902022392@163.com", "15522500416@163.com", null, subject, content);


}


public static Boolean SendEmail (string toaddress, String cs, string ms, string subject, string content) {
Boolean flag = false;


String mailserverhost = "smtp.exmail.qq.com";
String mailserverport = "25";
String userName = "service@raylinetech.com";
String password = "WLlrXJC83";
String mailserverhost = Global.getconfig ("Mailserverhost");
String Mailserverport = Global.getconfig ("Mailserverpart");
;
String userName = Global.getconfig ("UserName");
String Password = global.getconfig ("password");
string[] Toaddressarr = Toaddress.split (",");
String csarr[] = Cs.split (",");
String msarr[] = Org.apache.commons.lang3.StringUtils.isNotBlank (ms)? Ms.split (","): null;
string[] arrarchievlist = null;


Emailutil util = new Emailutil (Mailserverhost, Mailserverport, userName, password, Toaddressarr, Csarr, Msarr,
Subject, content, arrarchievlist);
Flag = Util.sendmail ();
SYSTEM.OUT.PRINTLN (flag);
return flag;
}


}


Class Mailsenderinfo {
IP and port of server which send mail
Private String Mailserverhost;
Private String Mailserverport = "";
Address of server which send mail
Private String fromaddress;
Address of server which receive mail
Private string[] toaddress;
Address of server which receive mail
Private string[] csaddress;
Address of server which receive mail
Private string[] msaddress;
User name and password of server which'll login and send mail
Private String UserName;
private String password;
If need authentication
Private Boolean validate = false;
Theme of mail
Private String subject;
Context of mail
Private String content;
File name of attachment in email
Private string[] attachfilenames;


/**
* Get Properties of mail conversation
*/
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[] Getcsaddress () {
return csaddress;
}


public void Setcsaddress (string[] csaddress) {
this.csaddress = csaddress;
}


Public string[] Getmsaddress () {
return msaddress;
}


public void Setmsaddress (string[] msaddress) {
this.msaddress = msaddress;
}


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;
}
}


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);
}
}

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.