161013, Java implementation of bulk mail with attachments

Source: Internet
Author: User
Tags mailmessage

To complete the Java Bulk Mail feature, you must first add the Mail.jar and Activation.jar packages
Here is an example of the message: import Java.io.file;import java.util.properties;import Java.util.vector;import javax.mail.internet.mimeutility;/*** Send Message Class * @author Shi Peng * @version 2016.10.19**/public class Mailsenderinfo {// The IP and port of the server sending the message is private string Mailserverhost;private string mailserverport = "25";//the address of the sender of the message is private string fromaddress ///Email recipient's address private string[] toaddress;//login Mail sending server username and password private string Username;private string password;// Whether you need authentication private Boolean validate = false;//message subject private string subject;//The text content of the message private string content;//The file name of the message attachment privat E String fileName = "";//attachment file collection private vector filename = new vector ();/*** get mail Session properties * @return */public Properties Getpropertie S () {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 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 textcontent) {this.content = textcontent;} Public String GETfilename () {return fileName;} public void Setfilename (String fileName) {this.filename = FileName;} Public Vector GetFile () {return file;} public void Setfile (Vector file) {this.file = file;} /**** Method Description: Convert the theme to Chinese * input parameter: string strtext* return type: */public string Transferchinese (String strText) {try {strText = Mimeutilit Y.encodetext (New String (Strtext.getbytes (), "GB2312"), "GB2312", "B"); catch (Exception e) {e.printstacktrace ();} return strText;}} ——————————————————— Import javax.mail.authenticator;import javax.mail.passwordauthentication;/*** e-Mail Authenticator * @ Author Shi Peng * @version 2016.10.19**/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;} Protected Passwordauthentication getpasswordauthentication () {return new passwordauthentication (userName, password);}} ——————————————————————— Import Java.io.file;import Java.util.date;import JAva.util.enumeration;import Java.util.properties;import Java.util.vector;import Javax.activation.DataHandler; Import Javax.activation.filedatasource;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.internetaddress;import Javax.mail.internet.MimeBodyPart; Import Javax.mail.internet.mimemessage;import Javax.mail.internet.mimemultipart;public class SimpleMailSender {/** * Send messages in text format * @param mailinfo messages to be sent */public Boolean sendtextmail (Mailsenderinfo mailinfo) {// Determine if identity authentication 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 sessionsession sendmailsession = Session.getdefaultinstance (pro,authenticator) for sending messages based on the mail session properties and password validator; try {// Create a mail message based on sessionMessage MailMessage = new MimeMessage (sendmailsession);//create Mail Sender address authenticatoraddress from = new InternetAddress ( Mailinfo.getfromaddress ());//Set the sender of the mail message Mailmessage.setfrom (from);//Create the recipient address of the message and set it to the mail message in string[] mailtoaddress = Mailinfo.gettoaddress (); int len = mailtoaddress.length; Address to[] = new Internetaddress[len]; for (int i=0;i<len;i++) {To[i] = new internetaddress (Mailtoaddress[i]);} The Message.RecipientType.TO property indicates that the recipient's type is to//to for the primary recipient, CC for CC, and Bcc for the secret cc. Mailmessage.setrecipients (message.recipienttype.to,to);//Set the subject of the mail message Mailmessage.setsubject (Mailinfo.getsubject () );//Set the time Mailmessage.setsentdate (new Date ()) to send the mail message, or//set the main content of the mail message string mailcontent = Mailinfo.getcontent (); Mailmessage.settext (mailcontent);//Send mail Transport.send (mailmessage); return true;} catch (Messagingexception ex) {ex.printstacktrace ();} return false;} /** *//*** send mail in HTML format * @param mailinfo message messages to be sent */public Boolean sendhtmlmail (Mailsenderinfo mailinfo) {// Determine if identity authentication is required myauthenticator authenticator = null; PropeRties Pro = Mailinfo.getproperties ();//If authentication is required, create a password validator if (Mailinfo.isvalidate ()) {authenticator = new Myauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());} Constructs a sessionsession sendmailsession = Session.getdefaultinstance (pro,authenticator) for sending messages based on the mail session properties and password validator; try {// Create a mail message based on session MailMessage = new MimeMessage (sendmailsession);//create mail Sender address from = new InternetAddress ( Mailinfo.getfromaddress ());//Set the sender of the mail message Mailmessage.setfrom (from);//Create the recipient address of the message and set it to the mail message in string[] mailtoaddress = Mailinfo.gettoaddress (); int len = mailtoaddress.length; Address to[] = new Internetaddress[len]; for (int i=0;i<len;i++) {To[i] = new internetaddress (Mailtoaddress[i]);} The Message.RecipientType.TO property indicates the recipient's type is to//mailmessage.setrecipient (Message.RecipientType.TO, to); Mailmessage.setrecipients (message.recipienttype.to,to);//Set the subject of the mail message Mailmessage.setsubject (Mailinfo.getsubject () );//sets the time mailmessage.setsentdate the mail message is sent (new Date ());//The Minimultipart class is a container class that contains objects of the MimeBodyPart type MultipaRT Mainpart = new Mimemultipart ();//Create a mimebodypartbodypart HTML containing HTML content = new MimeBodyPart ();// Set HTML content html.setcontent (Mailinfo.getcontent (), "text/html; Charset=utf-8″); Mainpart.addbodypart (HTML);//Add attachment to multipart vector file = Mailinfo.getfile (); String fileName = Mailinfo.getfilename (); Enumeration efile = File.elements (); while (Efile.hasmoreelements ()) {MimeBodyPart mdpfile = new MimeBodyPart (); fileName = Efile.nextelement (). toString (); Filedatasource FDS = new Filedatasource (fileName), Mdpfile.setdatahandler (New DataHandler (FDS));//This method can solve garbled problem string fileName1 = new String (Fds.getname (). GetBytes (), "iso-8859-1"); Mdpfile.setfilename (fileName1); Mainpart.addbodypart (Mdpfile);} File.removeallelements ();//Set Minimultipart object to message content mailmessage.setcontent (Mainpart);//Send mail Transport.send ( MailMessage); return true;} catch (Exception ex) {ex.printstacktrace ();} return false;}} ———————————————————————————— –import java.io.file;import Java.util.vector;import com.sun.mail.util.MailSSLSocketFaCtory;public class SendMail {public static void main (string[] args) {try {mailsenderinfo mailinfo = new Mailsenderinfo (); M Ailsslsocketfactory SF = new Mailsslsocketfactory (); Sf.settrustallhosts (true);//Set mail server type smtp.qq.com Smtp.exmail.qq.commailInfo.setMailServerHost ("smtp.qq.com");//Set the port number 25mailinfo.setmailserverport ("587");// Sets whether to verify Mailinfo.setvalidate (TRUE);//set user name, password, sender address Mailinfo.setusername ("1909083200"); Do not bring @qq.commailinfo.setpassword ("DOLSGBVWTTTTCHHD");//This is the authorization code obtained in the mailbox Mailinfo.setfromaddress ("[email  Protected] "); This must be completed/*** attachment */vector file = new Vector (); File F1 = new file ("D:/1.txt"); File.add (F1); mailinfo.setfile (file);/*** recipient mailbox * [email protected]*/string[] mailtoaddress = {"[email protected]"}; mailinfo.settoaddress (mailtoaddress); Mailinfo.setsubject ("Test"); Mailinfo.setcontent ("Registered address Baidu");//This class mainly to send mail simplemailsender SMS = new Simplemailsender ();//Sms.sendtextmail ( Mailinfo)///Send stylistic format if (Sms.sendhtmlmail (Mailinfo)) {System.out.println ("Mail Send true!”);} Send HTML format else{system.out.println ("Mail send false!");}} catch (Exception e) {e.printstacktrace ();}}} The above realized the javamail of the mass delivery function.

  

161013, Java implementation of bulk mail with attachments

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.