Java Mail email (with attachments) supports SSL

Source: Internet
Author: User

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 to send server userName with 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 {/** * e-mail (with attachments) * * @ PARAM mailinfo * Message to be sent */public Boolean sendhtmlandaffixmail (Mailsenderinfo mailinfo) {//Infer if authentication is required Mailaut Henticator 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 mail session properties and password authenticator; try { MimeMessage msg = new MimeMessage (session); Constructs the mimemessage and sets the primary 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 the Body mbpcontent.setcontent (Mailinfo.getcontent (), "text/html;charset=gb2312") to multipart; Mp.addbodypart ( mbpcontent);//Add to MimeMessage (multipart representative body) Vector file = Mailinfo.getattachfilenames (); Enumeration efile = File.elements ();//To MultipArt joins the attachment 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 representative annex) 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 (host);          Mailinfo.setmailserverport ("465");         Mailinfo.setvalidate (TRUE);         Mailinfo.setvalidatessl (TRUE);      Mailinfo.setusername ("username");      Mailinfo.setpassword ("pwd");//Your Mailbox password mailinfo.setfromaddress ("address");          Mailinfo.settoaddress ("[email protected]");          Mailinfo.setsubject ("Set mailbox Header"); Mailinfo.setcontent ("Today should be the Carnival day of Meizu powder!") "+" Today Meizu officially announced in Beijing MX4, Meizu MX4 adopted 5.36-inch 1920x1152 Resolution screen (PPI418), equipped with MediaTek eight-core processor, providing 20.7 million megapixel camera, equipped with 3100mAh battery, the implementation of 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 number, 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 email (with attachments) supports SSL

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.