JAVA--Send Google Mail


1 Introduction

There are also many Google emails sent on the Internet, and here is just to record some of the problems I encountered.

2. Mailbox configuration

1. Directly use the application-specific password: first turn on the two-step verification, and then configure the application-specific password.

Insert picture description here

2. Enable mailbox POP

Insert picture description here

2. Code

package com.tolern.base.util.email;

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

/**
 * @author Tomorrow
 * @date 2020/11/2 17:41
 */
public class GoogleTest {
    
    
    /*
     * gmail邮箱SSL方式
     */
    private static void gmailssl(Properties props) {
    
    
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        props.put("mail.debug", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
    }


    //gmail邮箱的TLS方式
    private static void gmailtls(Properties props) {
    
    
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
    }

    /**
     * 创建邮件内容 需科学上网
     *
     * @param sentToEmail 接收人邮箱
     * @return
     * @throws Exception
     */
    public static boolean getMimeMessage(String sentToEmail) throws Exception {
    
    
        //1.创建一封邮件的实例对象
        Properties props = new Properties();
        //选择ssl方式
        gmailtls(props);

        final String username = "[email protected]";// gmail 邮箱
        final String password = "123132";// Google应用专用密码
        // 当做多商户的时候需要使用getInstance, 如果只是一个邮箱发送的话就用getDefaultInstance
        // Session.getDefaultInstance 会将username,password保存在session会话中
        // Session.getInstance 不进行保存
        Session session = Session.getInstance(props,
                new Authenticator() {
    
    
                    protected PasswordAuthentication getPasswordAuthentication() {
    
    
                        return new PasswordAuthentication(username, password);
                    }
                });

        MimeMessage msg = new MimeMessage(session);
        //2.设置发件人地址
        msg.setFrom(new InternetAddress(sentToEmail));
        /**
         * 3.设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC:抄送
         * MimeMessage.RecipientType.BCC:密送
         */
        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(sentToEmail));
        //4.设置邮件主题
        msg.setSubject("To reset your password!", "UTF-8");

        // 6. 创建文本"节点"
        MimeBodyPart text = new MimeBodyPart();
        // 这里添加图片的方式是将整个图片包含到邮件内容中, 实际上也可以以 http 链接的形式添加网络图片
        text.setContent("<p>亲爱的用户:</p>" +
                        "<p>&nbsp; &nbsp; 您好! 您正在进行重置密码操作, 本次生成的密码为:</p>" +
                        "<p>&nbsp;&nbsp;&nbsp;&nbsp;\u200B" + 1234 + "&nbsp;(为了保障您帐号的安全性,请尽快修改密码)</p>" +
                        "<p><br></p><p>该邮件为系统自动发送, 请勿进行回复!</p>" +
                        "<p><br></p>",
                "text/html;charset=UTF-8");

        // 7. (文本+图片)设置 文本 和 图片"节点"的关系(将 文本 和 图片"节点"合成一个混合"节点")
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related");    // 关联关系


        // 11. 设置整个邮件的关系(将最终的混合"节点"作为邮件的内容添加到邮件对象)
        msg.setContent(mm_text_image);
        //设置邮件的发送时间,默认立即发送
        msg.setSentDate(new Date());

        Transport.send(msg);
        return true;
    }

    public static void main(String[] args) throws Exception {
    
    
        boolean mimeMessage = getMimeMessage("[email protected]");
        System.out.println(mimeMessage);
    }
}

The content can also be like this:

<div>
			<div style="text-align: center; border-bottom: 2px solid #ccc; padding: 20px 0;">
				<img style="width: 225px;" src="https://***-image.oss-eu-central-1***m/***/***.png" />
			</div>
			<div style="padding: 10px 25px;">
				<p style="font-size: 20px; font-family: 'arial'; color: rgba(0,0,0,0.9);">Hi (CLIENT_NAME)!</p>
				<div style="height: 5px;"></div>
				<p style="font-size: 20px; font-family: 'arial'; color: rgba(0,0,0,0.9);">Please click on the link below to verify your email address:</p>
				<div style="height: 10px;"></div>
				<a href="BINDING_EMAIL" style="display: block; text-decoration: none; background: #61B9AA;  text-align: center; height: 70px; line-height: 70px; margin: 0 auto; border-radius: 10px;" target="_blank" style="text-align:center;">
					<span style="font-family: arial; color: #fff;font-size: 22px;">
						Verify Email
					</span>
				</a>
				</p>
				<div style="height: 5px;"></div>
				<p style="font-size: 20px; font-family: 'arial'; color: rgba(0,0,0,0.9);">Or, if the link is not working, copy and paste this code in the app: <span style="color: #61B9AA;">NUMBER_EMAIL</span></p>
				<div style="height: 5px;"></div>
				<p style="font-size: 20px; font-family: 'arial'; color: rgba(0,0,0,0.9);">Happy charging!</p>
				<div style="height: 5px;"></div>
				<p style="font-size: 20px; font-family: 'arial'; color: rgba(0,0,0,0.9);">The Chargie Team</p>
			</div>
		</div>

3, notes

1. Because we are working with multiple merchants, the sender has been unsuccessful in switching at the time, and finally found that the wrong method was used. Session.getInstance
2. Application-specific password to avoid Google’s security check
3. If two-step verification is not enabled, it is required Do the following:
Open the access permissions of the less secure apps: https://myaccount.google.com/lesssecureapps
Insert picture description here
Allow access to the less secure apps: https://accounts.google.com/DisplayUnlockCaptcha
Insert picture description here

4. The server sends mail

1、安装mailx:yum install -y mailx
2、编辑配置文件:vim /etc/mail.rc
在最后面添加:
set smtp=smtps://smtp.gmail.com:465
set smtp-auth=login
set smtp-auth-user=cm646236438@gmail.com(自己的邮箱)
set smtp-auth-password=123132(应用专用密码)
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb/
3、验证发送邮件:echo "测试测试测试测试测试测试" | mail -v -s "测试测试测试测试" 646236438@qq.com

Guess you like

Origin blog.csdn.net/qq_38637558/article/details/109453887