使用465端口完成Java邮箱注册验证功能

昨天用阿里云上线部署我的一个项目,部署成功之后进行功能测试,发现注册功能用不了。最后查找资料发现是因为阿里云默认将25端口号屏蔽了,而我的应用程序中注册功能的实现就是用的25端口号。据阿里云提示需要改成465端口号才可以,于是上网查资料弄了好大一会儿,故在此记录一下。


一、前提

我的项目使用maven进行各种包的管理的,故需要添加依赖获取邮件注册组件。

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

二、MailService类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

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

/**
 * @Author: Evan
 * @Description:
 * @Date: Created in 19:07 2019/5/9
 * @Modified By:
 */

@Service
public class MailService {
    @Autowired
    private JavaMailSender sender;


    //username
    //在此处填写需要进行发送邮件的服务器
    //我的是163.com
    //需要开启pop3功能并使用客户端授权密码
    private final static String from="your email";
    //password
    //在此处填写
    private final static String psw="your password";

   //hostname
    private final static String host="smtp.163.com";
    /**
     * 使用加密的方式,利用465端口进行传输邮件,开启ssl
     * @param to    为收件人邮箱
     * @param message    发送的消息
     */
    public static boolean sendEmail(String to,String subject, String message) {
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            final String username = from;
            final String password = psw;
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            //通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            //设置发件人
            msg.setFrom(new InternetAddress(from));
            //设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            //设置邮件消息
            msg.setContent(message,"text/html;charset=utf-8");
            //msg.setText(message);
           // msg.setContent(text,"text/html;charset=UTF-8");
            //设置发送的日期
            msg.setSentDate(new Date());

            //调用Transport的send方法去发送邮件
            Transport.send(msg);
           return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

}

三、调用

//subject
		String subject="验证码验证";
				//validation code
		String code=(int)(Math.random()*10000)+"";
		String content="非常高兴您能加入我们,您本次的验证码为:"+code+"\n\n"+"再次感谢您的加入";
		boolean isSuccessful=MailService.sendEmail(email,subject,content);
		if(isSuccessful) {
			request.getSession().setAttribute("code", code);
			return ReturnMsg.msg(HttpServletResponse.SC_OK, "发送成功");
		}else {
			return ReturnMsg.msg(HttpServletResponse.SC_BAD_REQUEST, "发送失败");
		}
发布了32 篇原创文章 · 获赞 32 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Evan_love/article/details/90081103
今日推荐