1. Introduction to email
An email consists of a lot of information. The main information is as follows. Others are not considered for the time being, such as carbon copy, etc.:
1. Recipient: Recipient’s email address, such as [email protected]
2. Recipient name: It will be displayed when most emails are displayed, such as loadfate [email protected]
3. Sender: Sender’s email address
4. Sender’s name:
5. Subject: the title of the email
6. Content and attachments: the main content of the email
2. General steps for sending emails using Java
In general projects, there is no separate mail server. In general, other people's servers are used.
1. Set up the SMTP server: Different mail servers have different addresses. For example: smtp.qq.com represents Tencent’s SMTP server.
2. Authorization: Use the server’s account and password to log in to the server.
3. Create an email: Create an email containing all information, such as sender, recipient, content, etc.
4. Set the properties of the email: add data to the properties of the email.
5. Sending emails: Because the packages are different, the sending methods are inconsistent.
3. Java Mail and Apache Mail
Apache Mail is an 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 a jar package: mail.jar.
When using Apache Mail, you need to import two jar packages: mail.jar and commons-email-1.3.1.jar.
4. Use Java Mail to send emails
Copy the code code as follows:
public static void main(String[] args) throws Exception {
final String user = "779554589";
final String password = "";
String fromAddress = "[email protected]";
String toAddress = "[email protected]";
String subject = "Email test subject";
String content = "This is a test email<b>haha</b>";
//Configuration parameters
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 transport object to send email
{
//Generate session through parameters
Session session = Session.getInstance(props);
//Enable debug mode
session.setDebug(true);
//Create an email and set information
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setSubject(subject);
message.setText(content);
//Create transfer
Transport transport = session.getTransport();
//Connect to smtp server
transport.connect(user, password);
//send
transport.sendMessage(message, new InternetAddress[] { new InternetAddress(toAddress) });
transport.close();
}
//Method 2: Use the static method of the Transport class to send emails
{
//Get authorized connection when generating Session
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
session.setDebug(true);
//Create an email and set information
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");
//Send directly, the message is generated through the authorized Session
Transport.send(message);
}
}
5. Use Apache Mail to send emails
Copy the code code as follows:
public class ApacheMailTest {
// smtp server
private String hostName = "smtp.qq.com";
//Account and password
private String userName = "779554589";
private String password = "This is a secret";
// sender
private String fromAddress = "[email protected]";
// Sender's name
private String fromName = "loadfate";
public static void main(String[] args) throws Exception {
//Recipient and recipient name
String toAddress = "[email protected]";
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("Sending completed");
}
//Send a simple email, similar to 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 authorization information
email.setCharset("utf-8");
email.setFrom(fromAddress, fromName, "utf-8");//Set sender information
email.addTo(toAddress, toName, "utf-8");//Set recipient information
email.setSubject("Test Subject");//Set the subject
email.setMsg("This is a simple test!");//Set the email content
email.send();//Send email
}
//Send 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 an html email");
// Set the html content. In actual use, 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 an email with attachments");
email.setMsg("<a href='#'>Test content</a>");
//Add additional content to the email
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("D://mail.txt");//local file
// attachment.setURL(new URL("http://xxx/a.gif"));//remote file
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Description information");
// Set the attachment display name, which must be encoded, otherwise the Chinese will be garbled
attachment.setName(MimeUtility.encodeText("Mail.txt"));
//Add attachment to email
email.attach(attachment);
email.send();
}
}
6. Attachment project folder: maildemo
Download address: http://pan.baidu.com/s/1bn1Y6BX
If you have any questions or suggestions, please contact me
File description:
1. maildemo.zip: source code of maildemo
2. mail.jar: Jar package of Java Mail
3. commons-email-1.3.1.jar: jar package of Apache Mail