One minute to learn JavaMail (false) _ manual funny, one minute to learn javamail

Source: Internet
Author: User

One minute to learn JavaMail (false) _ manual funny, one minute to learn javamail

Because the company's internal office system (OA) needs to add a mail sending function, so I learned this feeling more unpopular JavaMail

 

1. Successful first:

 

2. Preparations: Although Java Mail is officially written, it is not integrated into jkd, so you need to write your own jar package

First go to the official website to download, or go to the CSDN (http://download.csdn.net/download/itsonglin/8632453)

 

 

3. paste a encapsulated tool-class code here, so you can copy it without looking at it. This makes it easy to use javamail without having to know what javamail is.

Ps

 

Import com. sun. mail. util. mailSSLSocketFactory; import java. io. *; import java. security. generalSecurityException; import java. util. *; import javax. activation. *; import javax. mail. *; import javax. mail. internet. *; public class SendMail {private String username = null; private String password = null; private Authenticator auth = null; private MimeMessage mimeMessage = null; private Properties pros = null; priv Ate Multipart multipart = null; private BodyPart bodypart = null;/*** steps required to initialize the account password and verify that * Create a MimeMessage object * sends an email: 1 * @ param username * @ param password */public SendMail (String username, String password) {this. username = username; this. password = password;}/*** set the email system parameter * to receive a map set whose key is of the string type and whose value is String * required steps for sending an email: 2 * @ param map */public void setPros (Map <String, String> map) {pros = new Proper Ties (); for (Map. entry <String, String> entry: map. entrySet () {pros. setProperty (entry. getKey (), entry. getValue () ;}}/*** required steps for initializing the MimeMessage object * to send an email: 3 */public void initMessage () {this. auth = new Email_Autherticator (); Session session = Session. getDefaultInstance (pros, auth); mimeMessage = new MimeMessage (session);}/*** steps required to verify the account password * to send an email * @ author Administrator **/public class Email_Auther Ticator extends Authenticator {public PasswordAuthentication getPasswordAuthentication () {return new PasswordAuthentication (username, password) ;}/ *** sets the basic parameters for sending emails (removing tedious email settings) * @ param sub set the mail subject * @ param text set the mail text content * @ param rec set the mail recipient * @ throws MessagingException * @ throws UnsupportedEncodingException */public void setdefamessagepros (String sub, string text, String rec) throws Messaging Exception, UnsupportedEncodingException {mimeMessage. setSubject (sub); mimeMessage. setText (text); mimeMessage. setRecipient (Message. recipientType. TO, new InternetAddress (rec); mimeMessage. setSentDate (new Date (); mimeMessage. setFrom (new InternetAddress (username, username);}/*** set Topic * @ param subject * @ throws MessagingException */public void setSubject (String subject) throws MessagingException {MimeMessage. setSubject (subject);}/*** set date * @ param Date * @ throws MessagingException */public void setDate (date) throws MessagingException {mimeMessage. setSentDate (new Date ();}/*** set the mail text content * @ param text * @ throws MessagingException */public void setText (String text) throws MessagingException {mimeMessage. setText (text);}/*** set the mail header * @ param arg0 * @ param arg1 * @ throws Messaging Exception */public void setHeader (String arg0, String arg1) throws MessagingException {mimeMessage. setHeader (arg0, arg1);}/*** set the email recipient address <sent by a single user> * @ param recipient * @ throws MessagingException */public void setRecipient (String recipient) throws MessagingException {mimeMessage. setRecipient (Message. recipientType. TO, new InternetAddress (recipient);}/*** set the email recipient address <sent by multiple users> * @ param list * @ throws MessagingException * @ throws AddressException */public String setRecipients (List <String> recs) throws AddressException, MessagingException {if (recs. isEmpty () {return "the recipient address is empty! ";}For (String str: recs) {mimeMessage. addRecipient (Message. RecipientType. TO, new InternetAddress (str);} return" the recipient address is added successfully! ";}/*** Set the email recipient address <send by multiple recipients> * @ param StringBuffer <parms, parms2, parms ......> * @ throws MessagingException * @ throws AddressException */@ SuppressWarnings ("static-access") public String setRecipients (StringBuffer sb) throws AddressException, messagingException {if (sb = null | "". equals (sb) {return "string data is empty! ";} Address [] address = new InternetAddress (). parse (sb. toString (); mimeMessage. addRecipients (Message. recipientType. TO, address); return "recipient added successfully ";} /*** set the email sender's name * @ param from * @ throws UnsupportedEncodingException * @ throws MessagingException */public void setFrom (String from) throws UnsupportedEncodingException, MessagingException {mimeMessage. setFrom (new InternetAddress (username, from ));} /*** Send an email <sent by a single user> * whether return is successfully sent * @ throws MessagingException */public String sendMessage () throws MessagingException {Transport. send (mimeMessage); return "success";}/*** sets the path of the file sent by the attachment * @ param file */public void setMultipart (String file) throws MessagingException, IOException {if (multipart = null) {multipart = new MimeMultipart ();} multipart. addBodyPart (writeFiles (file); mimeMessage. setCont Ent (multipart );} /*** set the attachment <add multiple attachments> * @ param fileList <collection of received lists> * @ throws MessagingException * @ throws IOException */public void setMultiparts (List <String> fileList) throws MessagingException, IOException {if (multipart = null) {multipart = new MimeMultipart () ;}for (String s: fileList) {multipart. addBodyPart (writeFiles (s);} mimeMessage. setContent (multipart);}/*** sends the text content and sets the encoding method * <used together with the attachment sending method> * <Use the setText () method to send common text content> * @ param s * @ param type * @ throws MessagingException */public void setContent (String s, String type) throws MessagingException {if (multipart = null) {multipart = new MimeMultipart ();} bodypart = new MimeBodyPart (); bodypart. setContent (s, type); multipart. addBodyPart (bodypart); mimeMessage. setContent (multipart); mimeMessage. saveChanges ();}/*** read attachment * @ param filePath * @ Return * @ throws IOException * @ throws MessagingException */public BodyPart writeFiles (String filePath) throws IOException, MessagingException {File file = new File (filePath); if (! File. exists () {throw new IOException ("the file does not exist! Make sure the file path is correct ");} bodypart = new MimeBodyPart (); DataSource dataSource = new FileDataSource (file); bodypart. setDataHandler (new DataHandler (dataSource); // encode the file name. Otherwise, garbled bodypart occurs. setFileName (MimeUtility. encodeText (file. getName (); return bodypart;}/*** use SSL to log on * @ throws GeneralSecurityException */public void openSSL () throws GeneralSecurityException {MailSSLSocketFactory sf = new MailSSLSocketFactory (); sf. setTrustAllHosts (true); pros. put ("mail. smtp. ssl. enable "," true "); pros. put ("mail. smtp. ssl. socketFactory ", sf );}}

 

Ps: code from http://blog.csdn.net/Coding_One/article/details/51354456

 

 

4. After you copy the code in place (remember to add your package name), you can directly use this tool class. The demo I wrote will be posted below.

 

Public void sendMailTest () throws IOException, MessagingException {// first create a sendMail object, which encapsulates the mail to an object, of course, you must first tell it your username and password SendMail sendMail = new SendMail ("your email address", "your email password "); // This indicates some configuration information, just like the framework configuration file Map <String, String> map = new HashMap <String, String> (); map. put ("mail. host "," smtp.qq.com "); // set the address of the mailbox server. I entered QQ mailbox here. If you do not know the address of the server where your mailbox is used, Baidu would be fine, this format is generally used, for example, 163 is smtp.163.com map. put ("mail. smtp. auth "," true "); // enable verification. If you are not sure how to send the verification, right? sendMail. setPros (map); // then tell the message you have written to it // initialize and verify if your password is correct with sendMail. initMessage (); sendMail. setSubject ("Enter the mail title here"); sendMail. setText ("enter the body here"); sendMail. setRecipient ("who do you want to send this parameter to"); sendMail. setFrom ("fill in your nickname and tell you who you are"); // fill in a bunch of messy things and finally send sendMail. sendMessage ();}

 

I always feel that this code style is a little ugly. It looks better for IDE.

 

This is just a simple demo. More groups, attachments, and attachments are supported in the tool class.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Just a split line that I haven't finished ------------------------------------------------------------------------------

 

One important thing is that if you use QQ mail, you do not need to fill in your QQ password, but the so-called authorization code (you need to apply in QQ mail, set-account-enable SMTP service)

 

 

 

Then enable ssl. The Code is as follows:

// Use ssl to log on to sendMail. openSSL ();

 

This addition can all be used (except after sending ..), It is best:

 

 

 

Then you can use the loop to harass your friends.

In this demo, you only need to enable ssl and use the authorization code, which is very simple!

 

 

 

 

This article prohibits Reprinting in all forms!

 

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.