Java uses Javax.mail.jar to send mail and agrees to send attachments

Source: Internet
Author: User

Because Java has a great advantage in developing Web pages. So as a leader in the web, such as sending text messages and sending e-mails, these are the inevitable, security of the network security we need to account for the security level mentioned higher. So these are the skills you have to master for developers! I have always thought that as a developer, not afraid of the development process encountered many problems, but have not to solve its courage and determination, here more learning becomes the key, become a programmer development of the most important! All right. Gossip is here. Come up with something practical.

When a developer works to a certain extent, the object-oriented mind will always be surrounded by his father. So we first put the message of the constant class, the entity class and the tool class and so on before the encapsulation of the package, the inheritance of inheritance! The code comes. Keep your eyes wide open:

/** * @Description:  * * @Title: Simplemail.java * @Package Com.joyce.bean * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 09:06:51 * @version V2.0 */package com.joyce.mail.bean;/** * @Description: Mail Message class *  * @c Lassname:simplemail * @Copyright: Copyright (c) *  * @author comsys-lzp * @date 2014-5-28 a.m. 09:06:51 * @version V 2.0 */public class Mail {/** * theme */private string subject;/** * Content */private String content;/** * @return the subject */p Ublic String Getsubject () {return subject;} /** * @param subject * The            subject to set */public void Setsubject (String subject) {this.subject = subject;} /** * @return The content */public String getcontent () {return content;} /** * @param content * The            content to set */public void SetContent (String content) {this.content = content;}}

What you see above is to send the message is generally indispensable message headers and message content, as in the use of a wide range of e-mail that inevitably encapsulated, OK. Next we look at the mailbox login class:
/** * @Description: * * @Title: Mailauthenticator.java * @Package Com.joyce.bean * @Copyright: Copyright (c) * * @au Thor COMSYS-LZP * @date 2014-5-28 Morning 08:59:11 * @version V2.0 */package com.joyce.mail.bean;import Javax.mail.Authenticato R;import javax.mail.passwordauthentication;/** * @Description: Email Login class * * @ClassName: Mailauthenticator * @Copyright: Copy Right (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 08:59:11 * @version V2.0 */public class Mailauthenticator Extend        s Authenticator {/** * username (login email) */private String username; /** * Password * */private string password;/** * @return the username */public string GetUserName () {return username;} /** * @param username the username to set */public void Setusername (String username) {this.username = username;} /** * @return The password */public String GetPassword () {return password;} /** * @param password The password to set */public void SetPassword (String password) {this.password = password;} /** * @param uSername * @param password */public mailauthenticator (string Username, string password) {this.username = Username;this.pas Sword = password;} @Overrideprotected passwordauthentication getpasswordauthentication () {return new passwordauthentication (username,    password); }}

The constant class that we need should come in here.
Package Com.joyce.mail.bean;import java.text.simpledateformat;import java.util.date;/** * @Description: Message Send constant class * * @ Classname:mailconstant * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 Morning 11:01:16 * @version V2 .0 */public class Mailconstant {public static final String mail_user = ' [email protected] '; public static final Strin G MAIL_PWD = "* * * *";p ublic static final Boolean mail_ifdebug = true;public static final String mail_content_charset = "Te Xt/html;charset=utf-8 "; public static final SimpleDateFormat SDF = new SimpleDateFormat ("yyyy mm month DD Day HH" @ SS-Sec E ");p ublic static final String MAIL _title = "********* Account Activation Code" + Sdf.format (new Date ());//message header public static string Getmailcontent (string content) { StringBuffer sb = new StringBuffer (); Sb.append ("<div style= ' width:1024px;height:auto;margin:0px auto; Background-color: #66CCFF; font-size:14px;font-family: Microsoft Jacob Black; border-radius:5px;padding:5px; ' ><center>

</b><br/><br/> "), Sb.append (" <b></b> "+content); Sb.append (" </div></div > "); return sb.tostring ();}}


Here's the point, look at the key parts of the email.
/** * @Description: * * @Title: Mailsender.java * @Package Com.joyce.service.impl * @Copyright: Copyright (c) * * @a Uthor COMSYS-LZP * @date 2014-5-28 Morning 09:03:08 * @version V2.0 */package com.hupu.nac.mail.sender;import java.io.file;impo RT Java.text.simpledateformat;import Java.util.arraylist;import Java.util.date;import Java.util.List;import Java.util.properties;import Java.util.vector;import Javax.activation.datahandler;import Javax.activation.filedatasource;import Javax.mail.bodypart;import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.session;import Javax.mail.transport;import Javax.mail.internet.addressexception;import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimebodypart;import Javax.mail.internet.mimemessage;import Javax.mail.internet.MimeMultipart ; Import Com.hupu.nac.mail.bean.mail;import Com.hupu.nac.mail.bean.mailauthenticator;import com.hupu.nac.mail.bean.mailconstant;/** * @Description: Mail Send class * * @ClassName: MailSender * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 09:03:08 * @version V2.0 */public class Mail Sender {/** * props file to send mail */private final transient properties props = new Properties ();/** * Mail server login Verification */private Tran Sient Mailauthenticator authenticator;/** * Email session */private Transient session session;/** * Initialize Mail sender * * @param smtph Ostname * SMTP mail server address * @param username * User name (address) to send mail * @param password * Password to send the message */p Ublic MailSender (Final string smtphostname, final string username,final string password) {init (username, password, smtpho Stname);} /** * Initialize the Mail sender * * @param username * To send the user name (address) of the message, and to resolve the SmtpServer address * @param password * Send the password of the message */p Ublic MailSender (final string username, final string password) {//resolves smtpserver by e-mail address. Works with most mailboxes final String smtphostname = "smtp." + Username.split ("@") [1];init (username, password, smtphostname);} /** * @Description: Initialize * * @param username * Send mailUsername (address) * @param password * password * @param smtphostname * SMTP Host Address * * @Title: Mailsender.java * @Copy Right:copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 09:18:31 * @version V2.0 */private void init (String Username, string password, string smtphostname) {//Initialize Propsprops.put ("Mail.smtp.host", Smtphostname);p rops.put (" Mail.smtp.auth "," true ");//Verify authenticator = new Mailauthenticator (username, password);//Create sessionsession = Session.getinstance (props, authenticator);//Print Some debugging information session.setdebug (MAILCONSTANT.MAIL_IFDEBUG);}            /** * @Description: Send mail * * @param recipient * Recipient Email * @param subject * Email subject * @param content * Message content * @throws addressexception * @throws messagingexception * * @Title: Mailsender.java * @Copyright: Copyrig HT (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 09:19:16 * @version V2.0 */public void Send (String recipient, Stri ng subject, Object content) throws Exception {Send (recipient, subject, content, null);} /** * Send mail * * @param recipient * Recipient Email * @param subject * Email subject * @param content * within the email * @param files * Accessories * @throws Exception * @author Joyce.luo * @date 2014-10-15 Morning 10:23:09 * @version V3.0 * @ Since tomcat6.0,jdk1.6 * @copyright: Copyright (c) */public void Send (String recipient, string subject, Object Conten T, vector<file> files) throws Exception {//create MIME type message final mimemessage message = new MimeMessage (session);//Set Sender M Essage.setfrom (New InternetAddress (Authenticator.getusername ()));//Set the recipient Message.setrecipient ( Message.RecipientType.TO, new InternetAddress (recipient));//Set Subject message.setsubject (subject);//Set message contents if (Null = = Files | | Files.size () = = 0) {message.setcontent (content.tostring (), mailconstant.mail_content_charset);} else {//create Mimemultipart add content (can include multiple attachments) Mimemultipart multipart = new Mimemultipart ();//mimebodypart (for letter Contents/attachments) BodyPart BodyPart = New MimeBodyPart (); Bodypart.setcontent (Content.tostriNg (), mailconstant.mail_content_charset);//Add to Mimemultipart object Multipart.addbodypart (BodyPart); for (int i = 0; i < Files.size (); i++) {File File = (file) files.elementat (i); String fname = File.getname ();//Create Filedatasource (to add attachment) filedatasource FDS = new Filedatasource (file); BodyPart Filebodypart = new MimeBodyPart ();//character stream form loading file Filebodypart.setdatahandler (new DataHandler (FDS));// Set the attachment file name Filebodypart.setfilename (fname); Multipart.addbodypart (Filebodypart); message.setcontent (multipart);}} Set the sending time Message.setsentdate (new Date ());//Store message information message.savechanges ();//message.setfilename (filename)// Send mail transport.send (message);}            /** * @Description: Mass Mailing * * @param recipients * Recipients * @param subject * Subject * @param content *  Content * @throws addressexception * @throws messagingexception * * @Title: Mailsender.java * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 09:20:24 * @version V2.0 */public void Send (List<string> recipient S, String subject, Object content) throws Exception {Send (recipients, subject, content, NULL);} /** * Bulk Mail * * @param recipients * Recipients * @param subject * Subject * @param content * Contents * @p Aram Files * Accessories * @throws Exception * @author Joyce.luo * @date 2014-10-15 a.m. 10:26:35 * @version V3.0 * @since  tomcat6.0,jdk1.6 * @copyright: Copyright (c) */public void Send (list<string> recipients, String subject, Object  Content, vector<file> files) throws Exception {//create MIME type message final mimemessage message = new MimeMessage (session);// Set Sender Message.setfrom (New internetaddress (Authenticator.getusername ()));//Set recipient final int num = Recipients.size (); I Nternetaddress[] addresses = new Internetaddress[num];for (int i = 0; i < num; i++) {addresses[i] = new internetaddress (Recipients.get (i));} Message.setrecipients (Message.RecipientType.TO, addresses);//Set Theme Message.setsubject (subject);//Set message contents if (Null = = Files | | Files.size () = = 0) {message.setcontent (cOntent.tostring (), mailconstant.mail_content_charset);}  else {//create Mimemultipart Add content (can include multiple attachments) Mimemultipart multipart = new Mimemultipart (); MimeBodyPart (for letter Contents/accessories) BodyPart BodyPart = new MimeBodyPart (); Bodypart.setcontent (Content.tostring (), Mailconstant.mail_content_charset); Add to Mimemultipart object Multipart.addbodypart (BodyPart); for (int i = 0; i < files.size (); i++) {File File = (file) files.e Lementat (i); String fname = File.getname ();//Create Filedatasource (to add attachment) filedatasource FDS = new Filedatasource (file); BodyPart Filebodypart = new MimeBodyPart ();//character stream form loading file Filebodypart.setdatahandler (new DataHandler (FDS));// Set the attachment file name fname = new String (fname.getbytes ("UTF-8"), "iso-8859-1"); Filebodypart.setfilename (fname); Multipart.addbodypart (Filebodypart); message.setcontent (multipart);}} Set the sending time Message.setsentdate (new Date ()),//Store message information message.savechanges ();//Send mail transport.send (message);} /** * @Description: Send mail * * @param recipient * Recipient Email * @param mail * Mail Object * @tHrows Exception * * @Title: Mailsender.java * @Copyright: Copyright (c) * * * @author COMSYS-LZP * @date 2014-5-28 morning 09:20:54 * @version V2.0 */public void Send (String recipient, mail mail) throws Exception {Send (recipient, mail.getsubject (), mail.getcontent ());}  /** * @Description: Bulk Mail * * @param recipients * Recipients * @param mail * Mail Object * @throws Exception * @Title: Mailsender.java * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 Morning 09:21:19 * @version V2.0 */public void Send (list<string> recipients, mail mail) throws Exception {Send (Recipients, Mail.getsubject (), M Ail.getcontent ());} /** * Bulk Mail * * @param recipients * Recipients * @param mail * Mail Object * @param files * Attachments * @thro WS Exception * @author Joyce.luo * @date 2014-10-15 a.m. 10:28:38 * @version V3.0 * @since tomcat6.0,jdk1.6 * @copyright: Cop Yright (c) */public void Send (list<string> recipients, mail mail, vector<file> files) tHrows Exception {Send (Recipients, Mail.getsubject (), mail.getcontent (), files);}} 


On the page of the activation Code or verification code this kind of do not have to say more
/** * @Description: * * @Title: Randomcodeutil.java * @Package com.joyce.mail.util * @Copyright: Copyright (c) 2014 * * @  Author Comsys-lzp * @date 2014-5-28 Morning 11:07:34 * @version V2.0 */package com.joyce.mail.util;/** * @Description: Random Code Tool Class * * @ClassName: Randomcodeutil * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 Morning 11:07:34 * @ver  Sion V2.0 */public class Randomcodeutil {/** * random code set */private static final string[] Randcode = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "a", "s", "D", "F", "G", "H", "J", "K", "L", "Z" , "X", "C", "V", "B", "N", "M"};/** * @Description: Generates random code of the specified length * * @param codelength * @return * * @Title: Randomcodeutil. Java * @Copyright: Copyright (c) * * @author COMSYS-LZP * @date 2014-5-28 a.m. 11:11:55 * @version V2.0 */public static String Randomcode (Integer codelength) throws Exception {try {stringbuffer code = new StringBuffer (); if (null = = Codelength || 0 = = codelength) {CodeLength = 4;} for (int i = 0; i < codelength; i++) {code.append (randcode[(int) Math.floor (math.random () * 36)]);} return code.tostring ();} catch (Exception e) {throw new RuntimeException ("Random Code Error");}}  /** * @Description: Generates random code with a length of 4 * * @return * @throws Exception * * @Title: Randomcodeutil.java * @Copyright: Copyright (c) * * @author comsys-lzp * @date 2014-5-28 pm 01:19:33 * @version V2.0 */public static String Randomcode () throws Excep Tion{return randomcode (null);}}

Ok. Send mail with Javax.mail.jar and you're done! Isn't it very easy. Complete demo resources;: http://download.csdn.net/download/luo201227/7446279

It's been a while. To update. In fact, there is nothing very much to say, just to mention it to you. If you are interested, be able to get to know the building of James Mail server!

Java uses Javax.mail.jar to send mail and agrees to send 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.