Javamail sends mail to share instance code

  • 2020-04-01 02:14:44
  • OfStack

Note: to import javamail's mail.jar .
The following three pieces of code are all my code, friends if you want to use, directly copy can.
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 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.mailServerHost);
        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[] attachFileNames) {
        this.attachFileNames = attachFileNames;
    }
    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 content) {
        this.content = content;
    }
}

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.AddressException;
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());
            //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());
            //Sets the main content of the mail message
            String mailContent = mailInfo.getContent();
             mailMessage.setText(mailContent);
             //Send E-mail
             Transport.send(mailMessage);
             return true;
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }
    
    public boolean sendHtmlMail(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());
            //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 MimeMultipart 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 mainPart object to the message content
             mailMessage.setContent(mainPart);
             //Send E-mail
             Transport.send(mailMessage);
             return true;
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.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;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
}

Here is the code to use the above three classes:

package com.util.mail;

public class Mail {
    
    public static void main(String[] args) {
        //This class is mainly for setting up mail
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.126.com");
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("test@126.com");
        mailInfo.setPassword("test");
        mailInfo.setFromAddress("test@126.com");
        mailInfo.setToAddress("test@qq.com");
        mailInfo.setSubject(" Set the mailbox title   Such as http://www.guihua.org  China osmanthus net ");
        mailInfo.setContent(" Set the email content   Such as http://www.guihua.org  China osmanthus net   It is the largest osmanthus website in China ==");
        //This class is mainly used to send mail
        SimpleMailSender sms = new SimpleMailSender();
        sms.sendTextMail(mailInfo);
        sms.sendHtmlMail(mailInfo);
    }
}

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: