Java - use java to send emails to mailboxes

Problem Description

  When we register a website every day or use a certain software to download, we need the registration function. When we register, the official app provider will send us an email to our email. When we click on the email, the activation is successful and the registration is complete, and then we can have the next login and download related functions. Therefore, it is very important to use java to send emails. This article uses java to realize the function of sending mail to the mailbox.

Implementation

  This article uses QQ mailbox as an example, and other mailboxes are similar. Before we write the code, we first need to log in to our QQ mailbox , and then set it up to obtain the POP3/SMTP service. The default is closed and we need to manually open it. The specific steps are:Settings—>Accounts—>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV Service—>POP3/SMTP Service. The specific operation process is as follows:


  Here we need to send a text message through our mobile phone number according to the prompt method, and then we can generate the corresponding activation code. The specific operations are as follows:

  The content sent by our mobile phone is as follows:

  After the SMS is sent successfully, then clickI have sentbutton, the corresponding activation code will be generated, this activation code is to be filled in our code, so it is recommended to copy, not to write by hand. If you make a mistake, your email will not be received. details as follows:

Code

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发邮件工具类
 */
public final class MailUtils {
    
    
    private static final String USER = "填你自己邮箱"; // 发件人称号,同邮箱地址
    private static final String PASSWORD = "填写刚才获得的授权码"; // 可以使户端授权码

    /**
     *
     * @param to 收件人邮箱
     * @param text 邮件正文
     * @param title 标题
     */
    /* 发送验证信息的邮件 */
    public static boolean sendMail(String to, String text, String title){
    
    
        try {
    
    
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");

            // 发件人的账号
            props.put("mail.user", USER);
            //发件人的密码
            props.put("mail.password", PASSWORD);

            // 构建授权信息,用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
    
    
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
    
    
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息,创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            return true;
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception {
    
     // 做测试用
        MailUtils.sendMail("填你自己邮箱","你好,这是一封测试邮件,无需回复。","测试邮件");
        System.out.println("发送成功");
    }
}

  What needs special attention here is: I hope readers will study the code, don't paste it directly 代码直接不可运行,会报错, you need to pay special attention. 需要填写自己的邮箱以及相应的授权码. After the code runs, the IDEA effect is as follows:

  This means that we have successfully sent the code, and the code is correct! ! ! Let's take a look at the mailbox to see if we have received the email:

  it seems that we succeeded, we received the email, opened one of the mailboxes, and we checked the contents, and there was a feeling of deja vu:

Summarize

  Sometimes we encounter some very interesting things during project development or learning, and we can record them. First, we can provide some help for the convenience of other small partners when they need it, and secondly, it is more We can view our own articles when we need to use them, which is equivalent to a notebook. Come on, people who work hard every day will be the most handsome, there will be, come on, code yuan! ! ! The future can be expected! ! ! ! ! ! ! ! ! ! ! ! !Today is the 2021S11 League of Legends global finals, I hope EDG can break through the siege and win the championship perfectly! ! ! The day the silver dragon is reforged, when the knight returns. Go EDG, Go LPL. I set up a Flag,要是EDG赢了,我就卸载英雄联,每天好好工作,注意休息!!!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324166741&siteId=291194637