实现邮件发送验证码

版权声明:原创内容是本人学习总结,仅限学习使用,禁止用于其他用途。如有错误和不足,欢迎评论指正补充。 https://blog.csdn.net/qian_qian_123/article/details/86654797

1、包

①maven项目下pom依赖:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
</dependency>

②spring boot maven项目下pom依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

③普通项目导包地址:

打开包地址进行下载(不建议)(建议使用maven)(或者自己去maven仓库下载需要的包)

2、工具类

package mainTest;

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

/**
 * 邮件工具类
 */
public class MailUtil {
	/**
	 * 发送邮件
	 * 
	 * @param to
	 *            发送对象(邮箱地址)
	 * @param text
	 *            发送内容
	 */
	public static void send_mail(String to, String text) throws MessagingException {
		// 创建连接对象 连接到邮件服务器
		Properties properties = new Properties();

		/**
		 * 设置发送邮件的基本参数
		 */
		// 发送邮件服务器
		// (注意,此处根据你的服务器来决定,如果使用的是QQ服务器,请填写smtp.qq.com)
		properties.put("mail.smtp.host", "smtp.qq.com");
		// 发送端口(根据实际情况填写,一般均为25)
		properties.put("mail.smtp.port", "25");
		properties.put("mail.smtp.auth", "true");
		// 设置发送邮件的账号和授权码
		Session session = Session.getInstance(properties, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 两个参数分别是发送邮件的账户和授权码
				// (注意,如果配置后不生效,请检测是否开启了 POP3/SMTP 服务,
				// QQ邮箱对应设置位置在: [设置-账户-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务])
				return new PasswordAuthentication("[email protected]", "hmojzrhqpakrghdj");
			}// aplsuhcidgvrgjbj
		});

		// 创建邮件对象
		Message message = new MimeMessage(session);
		// 设置发件人
		message.setFrom(new InternetAddress("[email protected]"));
		// 设置收件人
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		// 设置主题
		message.setSubject("这是一份测试邮件");
		// 设置邮件正文 第二个参数是邮件发送的类型
		message.setContent(text, "text/html;charset=UTF-8");
		// 发送一封邮件
		Transport.send(message);
	}
}

3、测试类

package mainTest;

import javax.mail.MessagingException;

/**
 * 测试类
 */
public class Test {
	public static void main(String[] args) {
		try {
			// 请将此处的 [email protected] 替换为您的收件邮箱号码
			String code = String.valueOf((int) (Math.random() * 9999));
			System.out.println(code);
			MailUtil.send_mail("[email protected]", "您的验证码为:" + code);
			System.out.println("邮件发送成功!");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}

代码结束,测试成功

猜你喜欢

转载自blog.csdn.net/qian_qian_123/article/details/86654797