使用SMTP进行邮箱推送

得到的AccessKey AccessSecret 作用于–调用单一发信 API-----SingleSendMail

设置的SMTP密码作用于–SMTP 协议发信----(可添加附件)

public void pushEmail(File file) {
    // 配置发送邮件的环境属性
    final Properties props = new Properties();
    // 表示SMTP发送邮件,需要进行身份验证
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", ALIDM_SMTP_HOST);
    props.put("mail.smtp.port", ALIDM_SMTP_PORT);

    props.put("mail.user", user);
    // 访问SMTP服务时需要提供的密码
    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);
    try {
        // 设置发件人
        InternetAddress fromAddress = new InternetAddress(user);
        message.setFrom(fromAddress);
        Address[] a = new Address[1];
        a[0] = new InternetAddress(senderEmail);
        message.setReplyTo(a);
        // 设置收件人
        InternetAddress to = new InternetAddress(recipientEmail);
        message.setRecipient(MimeMessage.RecipientType.TO, to);
        // 设置邮件标题
        message.setSubject(title);
        // 设置邮件的内容体
        //创建附件
        MimeBodyPart attch = new MimeBodyPart();
        DataHandler dh1 = new DataHandler(new FileDataSource(file));
        attch.setDataHandler(dh1);
        String filename1 = dh1.getName();
        // MimeUtility 是一个工具类,encodeText()用于处理附件字,防止中文乱码问题
        attch.setFileName(MimeUtility.encodeText(filename1));


        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(attch);
        message.setContent(mm);
        //保存修改
        message.saveChanges();
        // 发送邮件
        Transport.send(message);

    } catch (MessagingException e) {
        String err = e.getMessage();
        // 在这里处理message内容, 格式是固定的
        log.error("{}", err);
    } catch (UnsupportedEncodingException e) {
        log.error("{}", e);
    }
}

阿里云配置邮箱服务器
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值