Java Mail mail delivery (with attachments)

Source: Internet
Author: User
Tags mailmessage

Java mail message sent (with attachments) three classes

Mailsenderinfo.java

Package Mail;import java.util.Properties;        Import Java.util.vector;public class Mailsenderinfo {//The IP and port of the server sending the message private String mailserverhost;        Private String Mailserverport = "25";        Email Sender's address private String fromaddress;        The address of the mail recipient is private String toaddress;        Login Mail sending server username and password private String userName;        private String password;      Whether to require authentication private Boolean validate = false;        Whether to enable SSL private Boolean VALIDATESSL = false;        Message subject private String subject;        The text contents of the message are private String content;          The file name of the message attachment the private Vector 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;} 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;        The public void Setvalidate (Boolean validate) {this.validate = validate; } public Vector Getattachfilenames () {return attachfilenames;} public void Setattachfilenames (Vector 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 textcontent) {this.content = textcontent; }public Boolean Isvalidatessl () {return validatessl;}    public void Setvalidatessl (Boolean validatessl) {This.validatessl = Validatessl;}    }
Mailauthenticator.java

Package Mail;import javax.mail.*;p ublic class Mailauthenticator extends Authenticator {private String username;private String Password;public mailauthenticator () {}public Mailauthenticator (string Username, string password) {This.username = Username;this.password = password;} Protected Passwordauthentication getpasswordauthentication () {return new passwordauthentication (userName, password);}}

Simplemailsender.java

Package Mail;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  Import javax.mail.internet.mimeutility;/** * Simple Mail (mail with attachments) transmitter */public class Simplemailsender {/** * send mail in text format * * @param Mailinfo * Messages to be sent */public Boolean sendtextmail (Mailsenderinfo mailinfo) {//Determine if authentication required mailauthenticator AU Thenticator = null; Properties Pro = Mailinfo.getproperties (); if (Mailinfo.isvalidate ()) {//If authentication is required, create a password validator authenticator = new Mailauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());} According to the Mail willThe sessionsession sendmailsession = Session.getdefaultinstance (pro, authenticator) for sending a message is constructed by the session property 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 message in the message to = new InternetAddress (Mailinfo.gettoaddress ()); Mailmessage.setrecipient (Message.RecipientType.TO, to);// Set the subject Mailmessage.setsubject (Mailinfo.getsubject ()) of the mail message,//Set the time Mailmessage.setsentdate (new Date ()) to send the mail message;// Set the main contents 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 information to be sent */public static Boolean sendhtmlmail (Mailsenderinfo mailinfo) {//Determine if authentication is required mailauthenticator authenticator = null; Properties Pro = Mailinfo.getproperties ();//If authentication is required, create a password validator if (Mailinfo.isvaliDate ()) {authenticator = new Mailauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());} Constructs a Send mail sessionsession sendmailsession = session.getdefaultinstance (Pro, authenticator) based on mail session properties and password verifier; 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 message in the message to = new InternetAddress (Mailinfo.gettoaddress ());//The Message.RecipientType.TO property indicates that the recipient is of type tomailmessage.setrecipient ( 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 MimeBodyPart types of objects multipart Mainpart = new Mimemultipart ();//Create a Mimebodypartbodypart HTML = new MimeBodyPart () that contains HTML content;//Set HTML content html.setcontent ( Mailinfo.getcontent (), "text/html; Charset=utf-8 "); Mainpart.addbodypart (HTML);//Set Minimultipart object to message content mailmessage.setcontent (Mainpart);// Send Mail TranSport.send (MailMessage); return true;} catch (Messagingexception ex) {ex.printstacktrace ();} return false;} /** * Send messages in HTML (with attachments) * * @param mailinfo * Message */public boolean sendhtmlandaffixmail (Mailsenderinfo Mail Info) {//Determine if authentication is required mailauthenticator authenticator = null; Properties Pro = Mailinfo.getproperties (), if (Mailinfo.isvalidatessl ()) {pro.put ("mail.smtp.starttls.enable", "true" );p ro.put ("Mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");} If authentication is required, create a password validator if (Mailinfo.isvalidate ()) {authenticator = new Mailauthenticator (Mailinfo.getusername (), Mailinfo.getpassword ());} Constructs a sessionsession session = Session.getdefaultinstance (PRO, authenticator) for sending mail based on the mail session properties and password validator; try {MimeMessage msg = new MimeMessage (session); Constructs the mimemessage and sets the basic value//mimemessage msg = new MimeMessage (); Msg.setfrom (New InternetAddress (mailinfo.getfromaddress ());//Msg.addrecipients (Message.RecipientType.TO, address);////This can only be sent to a person emailmsg.setrecipients ( Message.recipienttype.To, Internetaddress.parse (Mailinfo.gettoaddress ())) Msg.setsubject (Mimeutility.encodetext (MailInfo.getSubject () )); Multipart MP = new Mimemultipart ();//construction Multipartmimebodypart mbpcontent = new MimeBodyPart ();// Add Body mbpcontent.setcontent (Mailinfo.getcontent (), "text/html;charset=gb2312") to multipart; Mp.addbodypart ( mbpcontent);//Add to MimeMessage (multipart for body) Vector file = Mailinfo.getattachfilenames (); Enumeration efile = File.elements ()//Add attachment to multipart while (efile.hasmoreelements ()) {MimeBodyPart mbpfile = new MimeBodyPart (); String filename = efile.nextelement (). toString (); System.out.println (Filename.tolowercase ()); Filedatasource FDS = new Filedatasource (filename), Mbpfile.setdatahandler (New DataHandler (FDS)); System.out.println (Fds.getname ()); Mbpfile.setfilename (Mimeutility.encodetext (Fds.getname ()));// Add to MimeMessage (multipart on behalf of attachment) Mp.addbodypart (mbpfile);} File.removeallelements ();//Add Mimemessagemsg.setcontent (MP) to multipart; Msg.setsentdate (new Date ()); Msg.savechanges ();//Send mail Transport TRAnsport = Session.gettransport ("SMTP"), Transport.connect (Mailinfo.getmailserverhost (), Mailinfo.getusername (), Mailinfo.getpassword ()); Transport.sendmessage (msg, msg.getallrecipients ()); Transport.close (); catch (Exception Mex) {mex.printstacktrace (); return false;} return true;}}
Test class

Package Mail;import Java.util.vector;public class MailTest {/** * @param args */public static void main (string[] args) {          This class is mainly set mail mailsenderinfo mailinfo = new Mailsenderinfo (); Mailinfo.setmailserverhost ("SMTP.          Xxxxxx.com ");          Mailinfo.setmailserverport ("465");         Mailinfo.setvalidate (TRUE);         Mailinfo.setvalidatessl (TRUE); Mailinfo.setusername ("[Email protected]<span style=" font-family:arial, Helvetica, Sans-serif; " >xxxxxx</span><span style= "font-family:arial, Helvetica, Sans-serif;"    >.com ");  </span> Mailinfo.setpassword (PWD);//Your email password mailinfo.setfromaddress (<span style= "font-family:arial, Helvetica, Sans-serif; " > "[Email protected]</span><span style=" font-family:arial, Helvetica, Sans-serif; " >xxxxxx</span><span style= "font-family:arial, Helvetica, Sans-serif;" >.com "</span><span style=" font-family:arial, Helvetica, Sans-serif; "    >); </Span> mailinfo.settoaddress ("[email protected]");          Mailinfo.setsubject ("Set mailbox Header"); Mailinfo.setcontent ("Today should be the Carnival day of Meizu powder!") "+" Today Meizu officially released MX4 in Beijing, Meizu MX4 5.36-inch 1920x1152 Resolution screen (PPI418), equipped with MediaTek eight-core processor, providing 20.7 million megapixel camera, equipped with 3100mAh battery, running the new FlyMe 4.0 system, Support Mobile and Unicom network double 4G, the Rabbit rabbit run 46124 points, provide dark gray, pure white and local tyrants Gold version, 16G version of 1799 Yuan, 32G version price of 1999 Yuan.             ");      This class is primarily to send mail vector fileNames = new vector ();      Filenames.add ("d:\\delete\\ Weekly Report 20140903103213.xls");      Filenames.add ("d:\\delete\\ copy of the weekly Report 20140903103213.xls");      Filenames.add ("d:\\delete\\ copy (2) Weekly Report 20140903103213.xls");      Mailinfo.setattachfilenames (FileNames);            Simplemailsender SMS = new Simplemailsender (); Sms.sendtextmail (mailinfo);//Send stylistic format sms.sendhtmlandaffixmail (mailinfo);//Send HTML format}}




Java Mail mail delivery (with attachments)

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.