Java mail sends a concrete example of a message

  • 2020-04-01 02:53:01
  • OfStack

Today, I learned about JavaMail. It is really a troublesome problem for JavaMail to send emails. In order to use in the future, I wrote a piece of code, into a jar, to facilitate the use of later. Ha ha

The following three pieces of code are all my code, friends if you want to use, directly copy can. Jar because I don't know how to get to the javaeye, so my friends go back and make their own.
My code has three classes:
The first class: mailsenderinfo.java


package com.util.mail;
 
import java.util.Properties; 
public class MailSenderInfo { 
 //The IP and port of the sending server
 private String mailServerHost; 
 private String mailServerPort = "25"; 
 //The address of the sender
 private String fromAddress; 
 //The address of the recipient
 private String toAddress; 
 //Login the username and password of the mail sending server
 private String userName; 
 private String password; 
 //Whether authentication is required
 private boolean validate = false; 
 //Email subject
 private String subject; 
 //The text content of the message
 private String content; 
 //File name of the message attachment
 private String[] attachFileNames;  
  
 public Properties getProperties(){ 
   Properties p = new Properties(); 
   p.put("mail.smtp.host", this.mailServerHost); 
   p.put("mail.smtp.port", this.mailServerPort); 
   p.put("mail.smtp.auth", validate ? "true" : "false"); 
   return p; 
 } 
 public String getMailServerHost() { 
   return mailServerHost; 
 } 
 public void setMailServerHost(String mailServerHost) { 
   this.mailServerHost = mailServerHost; 
 }
 public String getMailServerPort() { 
   return mailServerPort; 
 }
 public void setMailServerPort(String mailServerPort) { 
   this.mailServerPort = mailServerPort; 
 }
 public boolean isValidate() { 
   return validate; 
 }
 public void setValidate(boolean validate) { 
   this.validate = validate; 
 }
 public String[] getAttachFileNames() { 
   return attachFileNames; 
 }
 public void setAttachFileNames(String[] fileNames) { 
   this.attachFileNames = fileNames; 
 }
 public String getFromAddress() { 
   return fromAddress; 
 } 
 public void setFromAddress(String fromAddress) { 
   this.fromAddress = fromAddress; 
 }
 public String getPassword() { 
   return password; 
 }
 public void setPassword(String password) { 
   this.password = password; 
 }
 public String getToAddress() { 
   return toAddress; 
 } 
 public void setToAddress(String toAddress) { 
   this.toAddress = toAddress; 
 } 
 public String getUserName() { 
   return userName; 
 }
 public void setUserName(String userName) { 
   this.userName = userName; 
 }
 public String getSubject() { 
   return subject; 
 }
 public void setSubject(String subject) { 
   this.subject = subject; 
 }
 public String getContent() { 
   return content; 
 }
 public void setContent(String textContent) { 
   this.content = textContent; 
 } 
} 

The second class: simplemailsder.java


package com.util.mail;
import java.util.Date; 
import java.util.Properties;
import javax.mail.Address; 
import javax.mail.BodyPart; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 
 
public class SimpleMailSender  { 
 
 public boolean sendTextMail(MailSenderInfo mailInfo) { 
   //Determine if identification is required
   MyAuthenticator authenticator = null; 
   Properties pro = mailInfo.getProperties();
   if (mailInfo.isValidate()) { 
   //If authentication is required, a password validator is created
  authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); 
   }
   //Construct a session to send messages based on the message session property and password validator
   Session sendMailSession = Session.getDefaultInstance(pro,authenticator); 
   try { 
   //Create a mail message based on session
   Message mailMessage = new MimeMessage(sendMailSession); 
   //Create the sender address
   Address from = new InternetAddress(mailInfo.getFromAddress()); 
   //Set the sender of the mail message
   mailMessage.setFrom(from); 
   //Creates the recipient address of the message and sets it in the mail message
   Address to = new InternetAddress(mailInfo.getToAddress()); 
   mailMessage.setRecipient(Message.RecipientType.TO,to); 
   //Set the subject of the message
   mailMessage.setSubject(mailInfo.getSubject()); 
   //Set the time for the mail message to be sent
   mailMessage.setSentDate(new Date()); 
   //Sets the main content of the mail message
   String mailContent = mailInfo.getContent(); 
   mailMessage.setText(mailContent); 
   //Send E-mail
   Transport.send(mailMessage);
   return true; 
   } catch (MessagingException ex) { 
    ex.printStackTrace(); 
   } 
   return false; 
 } 

  
 public static boolean sendHtmlMail(MailSenderInfo mailInfo){ 
   //Determine if identification is required
   MyAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   //If authentication is required, a password validator & NBSP; is created.
   if (mailInfo.isValidate()) { 
  authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   } 
   //Construct a session to send messages based on the message session property and password validator
   Session sendMailSession = Session.getDefaultInstance(pro,authenticator); 
   try { 
   //Create a mail message based on session
   Message mailMessage = new MimeMessage(sendMailSession); 
   //Create the sender address
   Address from = new InternetAddress(mailInfo.getFromAddress()); 
   //Set the sender of the mail message
   mailMessage.setFrom(from); 
   //Creates the recipient address of the message and sets it in the mail message
   Address to = new InternetAddress(mailInfo.getToAddress()); 
   //Message. RecipientType. Said TO attribute of type TO the receiver
   mailMessage.setRecipient(Message.RecipientType.TO,to); 
   //Set the subject of the message
   mailMessage.setSubject(mailInfo.getSubject()); 
   //Set the time for the mail message to be sent
   mailMessage.setSentDate(new Date()); 
   //The MiniMultipart class is a container class that contains objects of type MimeBodyPart
   Multipart mainPart = new MimeMultipart(); 
   //Create a MimeBodyPart that contains HTML content
   BodyPart html = new MimeBodyPart(); 
   //Set the HTML content
   html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); 
   mainPart.addBodyPart(html); 
   //Set the MiniMultipart object to the mail content
   mailMessage.setContent(mainPart); 
   //Send E-mail
   Transport.send(mailMessage); 
   return true; 
   } catch (MessagingException ex) { 
    ex.printStackTrace(); 
   } 
   return false; 
 } 
} 

The third class: myauthenticator.java


package com.util.mail;
import javax.mail.*;

public class MyAuthenticator extends Authenticator{
 String userName=null;
 String password=null;

 public MyAuthenticator(){
 }
 public MyAuthenticator(String username, String password) { 
  this.userName = username; 
  this.password = password; 
 } 
 protected PasswordAuthentication getPasswordAuthentication(){
  return new PasswordAuthentication(userName, password);
 }
}

Here is the code to use the above three classes:


public static void main(String[] args){
         //This class is mainly for setting up mail
   MailSenderInfo mailInfo = new MailSenderInfo(); 
   mailInfo.setMailServerHost("smtp.163.com"); 
   mailInfo.setMailServerPort("25"); 
   mailInfo.setValidate(true); 
   mailInfo.setUserName("han2000lei@163.com"); 
   mailInfo.setPassword("**********");//Your email password
   mailInfo.setFromAddress("han2000lei@163.com"); 
   mailInfo.setToAddress("han2000lei@163.com"); 
   mailInfo.setSubject(" Set the mailbox title "); 
   mailInfo.setContent(" Set the email content "); 
         //This class is mainly used to send mail
   SimpleMailSender sms = new SimpleMailSender();
          sms.sendTextMail(mailInfo);//Sending style format
          sms.sendHtmlMail(mailInfo);//Send HTML format
 }

Finally, here are some tips for friends:
1. With this code, you can complete the email sending function of your javamail. Three classes are indispensable.
2. I package these three classes with com.util. Mail package. If you don't like it, you can change it yourself, but the three class files must be in the same package
3. Do not use your newly registered mailbox to send emails in the program. If your mailbox 163 is newly registered, do not use "smtp.163.com". Because you can't send it. The newly registered mailbox will not give you this permission, that is, you cannot pass the verification. Use your regular email address for a long time.
4, another problem is the mailInfo. SetMailServerHost (" smtp.163.com "); With the mailInfo. SetFromAddress (" han2000lei@163.com "); These two sentences. That is, if you use 163smtp server, then the email address must be 163 mailbox, if not, will not be sent successfully.
5. There are many online explanations for javamail's validation errors, but I can only see one. That's my third class. As long as you copy the whole code, I don't think there will be any problem.


Related articles: