Java Mail and Apache Mail sending Mail examples
- 2020-04-01 03:32:14
- OfStack
I. introduction to email
An email is composed of a lot of information, the main information is as follows, other temporarily ignored, such as cc, etc. :
1. Recipient: the recipient's email address, e.g. (link: #)
2. Recipient name: most emails will be displayed, such as "loadfate" (link: #)
3. Sender: the sender's email address
4. Sender's name:
5. Subject: the subject of the email
6. Contents and attachments: main contents of the email
Two, using Java to send mail general steps
A typical project does not have a separate mail server, and usually USES someone else's server.
1. Set up SMTP server: different mail servers have different addresses, for example: smtp.qq.com represents tencent's SMTP server.
2. Authorization: use the account and password of the server to log in the server.
Create a message: create a message that contains all the information, such as sender, recipient, content, etc.
4. Set the attributes of the message: add data to the attributes of the message.
5, send mail: because of different packaging, the way of sending is not consistent.
Java Mail and Apache Mail
Apache Mail is the encapsulation of Java Mail, which is easier to use and has a better sense of logical hierarchy.
To use Java Mail, you only need to import one jar: mail.jar.
When using Apache Mail, you need to import two jars: mail.jar and commons-email-1.3.1.jar.
Four, use Java Mail to send Mail
public static void main(String[] args) throws Exception {
final String user = "779554589";
final String password = "";
String fromAddress = "779554589@qq.com";
String toAddress = "loadfate@163.com";
String subject = " Email test subject ";
String content = " This is a test email <b> Ha ha </b>";
//Configuration parameter
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.qq.com");
//Method 1: use the transport object to send mail
{
//Generate a session
with arguments
Session session = Session.getInstance(props);
//Enable debug mode
session.setDebug(true);
//Create a message and set the message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setSubject(subject);
message.setText(content);
//Create a transport
Transport transport = session.getTransport();
//Connect to SMTP server
transport.connect(user, password);
//Send < br / >
transport.sendMessage(message, new InternetAddress[] { new InternetAddress(toAddress) });
transport.close();
}
//Method 2: use the Transport class static method to send mail
{
//Session is generated to obtain an authorization connection
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
session.setDebug(true);
//Create a message and set the message
Message message = new MimeMessage(session);
message.setSubject(subject);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipient(RecipientType.TO, new InternetAddress(toAddress));
message.setContent(content, "text/html;charset=utf-8");
//Directly, message generates
through an authorized Session
Transport.send(message);
}
}
Use Apache Mail to send emails
public class ApacheMailTest {
//SMTP server
private String hostName = "smtp.qq.com";
//Account number and password
private String userName = "779554589";
private String password = " It's a secret ";
//Sender
private String fromAddress = "779554589@qq.com";
//Sender name
private String fromName = "loadfate";
public static void main(String[] args) throws Exception {
//Addressee and addressee name
String toAddress = "loadfate@163.com";
String toName = "loadfate";
ApacheMailTest test = new ApacheMailTest();
//All exceptions are handled for easy browsing
test.sendSimpleEmail(toAddress, toName);
test.sendHtmlEmail(toAddress, toName);
test.sendMultiPartEmail(toAddress, toName);
System.out.println(" Send complete ");
}
//Send a simple message, like a message
public void sendSimpleEmail(String toAddress, String toName) throws Exception {
SimpleEmail email = new SimpleEmail();
email.setHostName(hostName);//Set SMTP server
email.setAuthentication(userName, password);//Set the authorization information
email.setCharset("utf-8");
email.setFrom(fromAddress, fromName, "utf-8");//Set the sender message
email.addTo(toAddress, toName, "utf-8");//Set the recipient information
email.setSubject(" The test subject ");//Set the topic
email.setMsg(" This is an easy test! ");//Set the message content to
email.send();//Send message
}
//Send an email with Html content
public void sendHtmlEmail(String toAddress, String toName) throws Exception {
HtmlEmail email = new HtmlEmail();
email.setHostName(hostName);
email.setAuthentication(userName, password);
email.setCharset("utf-8");
email.addTo(toAddress, toName, "utf-8");
email.setFrom(fromAddress, fromName, "utf-8");
email.setSubject(" This is a html mail ");
//Set the HTML content so that when you actually use it, you can read the written HTML code from the text
email.setHtmlMsg("<div style='width:100px;height:200px;'>a</div>");
email.send();
}
//Send complex emails, including attachments, etc.
public void sendMultiPartEmail(String toAddress, String toName) throws Exception {
MultiPartEmail email = null;
email = new MultiPartEmail();
email.setHostName(hostName);
email.setAuthentication(userName, password);
email.setCharset("utf-8");
email.addTo(toAddress, toName, "utf-8");
email.setFrom(fromAddress, fromName, "utf-8");
email.setSubject(" This is the email with attachment ");
email.setMsg("<a href='#'> The test content </a>");
//Add additional content to the message
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("D:\ mail .txt");//Local file
// attachment.setURL(new URL("http://xxx/a.gif"));// The remote file
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(" Description information ");
//Set the attachment to display the name, must be coded, or Chinese will be garbled
attachment.setName(MimeUtility.encodeText(" mail .txt"));
//Add an attachment to the message
email.attach(attachment);
email.send();
}
}
Sixth, the attachment
Project folder: maildemo
Download address: (link: http://pan.baidu.com/s/1bn1Y6BX)
If you have any questions or Suggestions, please contact me
Document description:
1. Maildemo.zip :maildemo source code
2. Mail.jar: jar package of Java mail
3. Commons-email-1.3.1.jar :Apache Mail jar package