一个Java发送邮件的案例

经常有些要发送邮件的需求,但是去网上拷代码老是拷不到能直接运行的,还经常要去以前的项目里面拷,今天直接发出来算了,免得每次都要去别的项目拷。

(只支持发送简单的文本文件,发附件的稍微复杂一丢丢,这里就不贴出来了)

依赖:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

源代码:

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

public class SendIdentifyingCode {

    public SendIdentifyingCode(String address, String content) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        //用465端口
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport ts = null;
        try {
            ts = session.getTransport();
            //下面这行自己用自己的噢,最后那个参数在我下面那个图里面开启点两下就可以找到了
            ts.connect("smtp.qq.com", "ohgreenorangestack@foxmail.com", "xxxxxxxxxxx");
            Message message = createSimpleMail(session, address, content);
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                assert ts != null;
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    private MimeMessage createSimpleMail(Session session, String address, String content) throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("ohgreenorangestack@foxmail.com"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject("FaceProcessor验证消息");//邮件标题
        message.setContent(content, "text/html;charset=UTF-8");//支持html格式
        return message;
    }

}

这边用的QQ邮箱

端口报错的话就用25,但是云服务器不让你用25端口,465端口是用的SSL,用这端口屁事比较多,jdk版本稍微高一点的话把SSL禁用了

解决方案https://blog.csdn.net/ooblack/article/details/119300423

然后要是能用25的话尽量用25得了,但是云服务器去申请25解封通过率不高

贴一个各个邮箱对应的端口

https://www.cnblogs.com/ni-huang-feng-wu/p/14773917.html

SpringBoot又把这玩意又封装了一次,如果是Spring忠实粉丝的话可以去用SpringBoot的

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.5.6</version>
</dependency>

接下来怎么写自行百度。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值