A simple example of javamail sending emails

Source: Internet
Author: User
Tags mailmessage

Today, I learned about JavaMail. It is really troublesome to send an email to javamail. For future convenience, I wrote some code and made it into a jar package to facilitate future use. Haha

The following three pieces of code are all my codes. If you want to use them, copy them directly.

First Class: MailSenderInfo. java

01
Package com. util. mail;
02
/**
03
* Basic information required for sending emails
04
* Author by wangfun
05
*/
06
Import java. util. Properties;
07
Public class MailSenderInfo {
08
// IP address and port of the server sending the mail
09
Private String mailServerHost;
10
Private String mailServerPort = "25 ";
11
// The sender's address
12
Private String fromAddress;
13
// Email recipient's address
14
Private String toAddress;
15
// Log on to the email sending server's username and password
16
Private String userName;
17
Private String password;
18
// Whether authentication is required
19
Private boolean validate = false;
20
// Email Subject
21
Private String subject;
22
// Text of the email
23
Private String content;
24
// File Name of the email attachment
25
Private String [] attachFileNames;
26
/**
27
* Get mail session attributes
28
*/
29
Public Properties getProperties (){
30
Properties p = new Properties ();
31
P. put ("mail. smtp. host", this. mailServerHost );
32
P. put ("mail. smtp. port", this. mailServerPort );
33
P. put ("mail. smtp. auth", validate? "True": "false ");
34
Return p;
35
}
36
Public String getMailServerHost (){
37
Return mailServerHost;
38
}
39
Public void setMailServerHost (String mailServerHost ){
40
This. mailServerHost = mailServerHost;
41
}
42
Public String getMailServerPort (){
43
Return mailServerPort;
44
}
45
Public void setMailServerPort (String mailServerPort ){
46
This. mailServerPort = mailServerPort;
47
}
48
Public boolean isValidate (){
49
Return validate;
50
}
51
Public void setValidate (boolean validate ){
52
This. validate = validate;
53
}
54
Public String [] getAttachFileNames (){
55
Return attachFileNames;
56
}
57
Public void setAttachFileNames (String [] fileNames ){
58
This. attachFileNames = fileNames;
59
}
60
Public String getFromAddress (){
61
Return fromAddress;
62
}
63
Public void setFromAddress (String fromAddress ){
64
This. fromAddress = fromAddress;
65
}
66
Public String getPassword (){
67
Return password;
68
}
69
Public void setPassword (String password ){
70
This. password = password;
71
}
72
Public String getToAddress (){
73
Return toAddress;
74
}
75
Public void setToAddress (String toAddress ){
76
This. toAddress = toAddress;
77
}
78
Public String getUserName (){
79
Return userName;
80
}
81
Public void setUserName (String userName ){
82
This. userName = userName;
83
}
84
Public String getSubject (){
85
Return subject;
86
}
87
Public void setSubject (String subject ){
88
This. subject = subject;
89
}
90
Public String getContent (){
91
Return content;
92
}
93
Public void setContent (String textContent ){
94
This. content = textContent;
95
}
96
}
Second Class: SimpleMailSender. java
001
Package com. util. mail;
002

003
Import java. util. Date;
004
Import java. util. Properties;
005
Import javax. mail. Address;
006
Import javax. mail. BodyPart;
007
Import javax. mail. Message;
008
Import javax. mail. MessagingException;
009
Import javax. mail. Multipart;
010
Import javax. mail. Session;
011
Import javax. mail. Transport;
012
Import javax. mail. internet. InternetAddress;
013
Import javax. mail. internet. MimeBodyPart;
014
Import javax. mail. internet. MimeMessage;
015
Import javax. mail. internet. MimeMultipart;
016

017
/**
018
* Simple email (email without attachments) sender
019
*/
020
Public class SimpleMailSender {
021
/**
022
* Send emails in text format
023
* @ Param mailInfo information of the email to be sent
024
*/
025
Public boolean sendTextMail (MailSenderInfo mailInfo ){
026
// Determine whether identity authentication is required
027
MyAuthenticator authenticator = null;
028
Properties pro = mailInfo. getProperties ();
029
If (mailInfo. isValidate ()){
030
// If You Need identity authentication, create a password authenticator
031
Authenticator = new MyAuthenticator (mailInfo. getUserName (), mailInfo. getPassword ());
032
}
033
// Construct a mail sending session based on the mail session attribute and the password validator
034
Session sendMailSession = Session. getDefaultInstance (pro, authenticator );
035
Try {
036
// Create an email message based on the session
037
Message mailMessage = new MimeMessage (sendMailSession );
038
// Create the mail sender address
039
Address from = new InternetAddress (mailInfo. getFromAddress ());
040
// Set the sender of the email message
041
MailMessage. setFrom (from );
042
// Create the email receiver address and set it to the email message
043
Address to = new InternetAddress (mailInfo. getToAddress ());
044
MailMessage. setRecipient (Message. RecipientType. TO, );
045
// Set the subject of the email message
046
MailMessage. setSubject (mailInfo. getSubject ());
047
// Set the mail message sending time
048
MailMessage. setSentDate (new Date ());
049
// Set the main content of the email message
050
String mailContent = mailInfo. getContent ();
051
MailMessage. setText (mailContent );
052
// Send an email
053
Transport. send (mailMessage );
054
Return true;
055
} Catch (MessagingException ex ){
056
Ex. printStackTrace ();
057
}
058
Return false;
059
}
060

061
/**
062
* Send emails in HTML Format
063
* @ Param mailInfo refers to the mail information to be sent.
064
*/
065
Public static boolean sendHtmlMail (MailSenderInfo mailInfo ){
066
// Determine whether identity authentication is required
067
MyAuthenticator authenticator = null;
068
Properties pro = mailInfo. getProperties ();
069
// If You Need identity authentication, create a password authenticator
070
If (mailInfo. isValidate ()){
071
Authenticator = new MyAuthenticator (mailInfo. getUserName (), mailInfo. getPassword ());
072
}
073
// Construct a mail sending session based on the mail session attribute and the password validator
074
Session sendMailSession = Session. getDefaultInstance (pro, authenticator );
075
Try {
076
// Create an email message based on the session
077
Message mailMessage = new MimeMessage (sendMailSession );
078
// Create the mail sender address
079
Address from = new InternetAddress (mailInfo. getFromAddress ());
080
// Set the sender of the email message
081
MailMessage. setFrom (from );
082
// Create the email receiver address and set it to the email message
083
Address to = new InternetAddress (mailInfo. getToAddress ());
084
// The Message. RecipientType. TO attribute indicates that the type of the recipient is
085
MailMessage. setRecipient (Message. RecipientType. TO, );
086
// Set the subject of the email message
087
MailMessage. setSubject (mailInfo. getSubject ());
088
// Set the mail message sending time
089
MailMessage. setSentDate (new Date ());
090
// The MiniMultipart class is a container class that contains objects of the MimeBodyPart type.
091
Multipart mainPart = new MimeMultipart ();
092
// Create a MimeBodyPart containing HTML content
093
BodyPart html = new MimeBodyPart ();
094
// Set HTML content
095
Html. setContent (mailInfo. getContent (), "text/html; charset = UTF-8 ");
096
MainPart. addBodyPart (html );
097
// Set the MiniMultipart object to the Mail content
098
MailMessage. setContent (mainPart );
099
// Send an email
100
Transport. send (mailMessage );
101
Return true;
102
} Catch (MessagingException ex ){
103
Ex. printStackTrace ();
104
}
105
Return false;
106
}
107
}
Third class: MyAuthenticator. java
01
Package com. util. mail;
02

03
Import javax. mail .*;
04

05
Public class MyAuthenticator extends Authenticator {
06
String userName = null;
07
String password = null;
08

09
Public MyAuthenticator (){
10
}
11
Public MyAuthenticator (String username, String password ){
12
This. userName = username;
13
This. password = password;
14
}
15
Protected PasswordAuthentication getPasswordAuthentication (){
16
Return new PasswordAuthentication (userName, password );
17
}
18
}
The following code uses the above three classes:
01
Public static void main (String [] args ){
02
// This class is mainly used to set emails
03
MailSenderInfo mailInfo = new MailSenderInfo ();
04
MailInfo. setMailServerHost ("smtp.163.com ");
05
MailInfo. setMailServerPort ("25 ");
06
MailInfo. setValidate (true );
07
MailInfo. setUserName ("han2000lei@163.com ");
08
MailInfo. setPassword ("***********"); // your email password
09
MailInfo. setFromAddress ("han2000lei@163.com ");
10
MailInfo. setToAddress ("han2000lei@163.com ");
11
MailInfo. setSubject ("set the mailbox title such as http://www.guihua.org China Osmanthus network ");
12
MailInfo. setContent ("set email content such as http://www.guihua.org China Osmanthus network is China's largest Osmanthus website = ");
13
// This class mainly sends emails
14
SimpleMailSender sms = new SimpleMailSender ();
15
Sms. sendTextMail (mailInfo); // sending Style
16
Sms. sendHtmlMail (mailInfo); // sends the message in html format.
17
}
Finally, I will give my friends some notes:
1. You can use this code to complete the javamail mail sending function. Three categories are indispensable.
2. I package the com. util. mail package for these three classes. If you do not like the package, you can change it by yourself, but the three class files must be in the same package.
3. Do not use the email address you just registered to send emails in the program. If your 163 email address is just registered, do not use "smtp.163.com ". Because you cannot send it out. The newly registered email address does not give you such permissions, that is, you cannot pass verification. It takes a long time to use your frequently used email address.
4. Another problem is mailInfo. setMailServerHost ("smtp.163.com"); and mailInfo. setFromAddress ("www.2cto.com. That is, if you use the 163smtp server, you must use the 163 email address to send the email. If you do not use the email address, the email will not be sent successfully.
5. There are many online explanations about javamail verification errors, but I only see one. Is my third class. As long as you copy all the code, I think there will be no problem.
Author Quttap

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.