java代码邮件发送从简单到项目

简单的邮件发送

首先要对发件人邮箱进行授权码,在设置中打开协议
在这里插入图片描述
在这里插入图片描述

package com.ruby.controller;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Description 简单邮件发送
 * @Author Ruby
 * @Date 2020/11/16 13:07
 * @Version 1.0
 */
public class JavaMail {

    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        //发送服务器需要身份验证
        properties.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        properties.setProperty("mail.transport.protocol", "smtp");
        // smtp服务器地址
        properties.put("mail.smtp.host", "smtp.163.com");
        
       //使用JavaMail发送邮件的5个步骤
        //1.创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(properties);
        // 设置为debug模式, 可以查看详细的发送 log
        session.setDebug(true);
        //2.通过session得到transport对象
        //发件人邮箱授权码
        Transport transport = session.getTransport();
        //3、使用邮箱的用户名和授权码连上邮件服务器
        transport.connect("******fa@163.com","****(代表授权码)");
       //4、创建邮件
        //邮件内容
        Message msg = new MimeMessage(session);
        msg.setSubject("邮件标题");
        msg.setText("邮件内容");
        //发件人邮箱
        msg.setFrom(new InternetAddress("******fa@163.com"));
        //收件人邮箱
        msg.setRecipient(Message.RecipientType.TO,
                new InternetAddress("******shou@163.com"));
        msg.saveChanges();
       //5、发送邮件
        transport.sendMessage(msg, msg.getAllRecipients());

        System.out.println("邮件发送成功...");
        transport.close();
    }
}

如果没有打开授权码就会有报这种问题
在这里插入图片描述
正常执行之后的程序是
在这里插入图片描述

邮件如图所示:
在这里插入图片描述

spring 整合发送邮件

配置jar包

<dependency>
   <groupId>javax.mail</groupId>
   <artifactId>mail</artifactId>
   <version>1.5.0-b01</version>
</dependency>
/**配置类
*/
package com.ruby.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;
@Configuration
public class MailConfig {
private static final String emailProtocol= **;
private static final String emailHost= **;
//邮箱名称
private static final String emailUsername= **;
//邮箱密码
private static final String emailPassword= **;
    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setProtocol(emailProtocol);
        javaMailSender.setHost(emailHost);
        javaMailSender.setPort(emailPort);
        javaMailSender.setUsername(emailUsername);
        javaMailSender.setPassword(emailPassword);
        javaMailSender.setDefaultEncoding("UTF-8");
        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.auth", true);
        javaMailProperties.put("mail." + emailProtocol + ".timeout", 3000);
        javaMailSender.setJavaMailProperties(javaMailProperties);
        return javaMailSender;
    }
package com.ruby.send;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.internet.MimeMessage;

/**
 * @Description
 * @Author Ruby
 * @Date 2020/11/27 16:21
 * @Version 1.0
 */
@Controller
@RequestMapping("send")
public class send{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private JavaMailSender javaMailSender;

   //发送方邮箱名称
   private static final String emailUsername= **;
  private static final String UA = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
   private String appendixUrl =**;

    /**
     * 发送邮件
     */
    @RequestMapping("/sendMail")
    @ResponseBody
    public boolean sendMail() {
            try {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
                messageHelper.setFrom(emailUsername);
               //接收方邮箱名称 
                messageHelper.setTo("**");
                messageHelper.setSubject("你好");
                messageHelper.setText("这是一封邮件");
                javaMailSender.send(mimeMessage);
                log.info("1111111111");
            } catch (Exception e) {
                log.error("邮件发送异常: ", e);
                return false;
            }
        return true;
    }

    /**
     * 发送带附件的邮件
     */
    @RequestMapping("/sendAttachMail")
    @ResponseBody
    public boolean sendAttachMail() {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(emailUsername);
            //接收方的邮件地址
            messageHelper.setTo("**");
            messageHelper.setSubject("你好");
            messageHelper.setText("这是一封邮件");
            URLConnection httpURLConnection = null;
            try {
                httpURLConnection = getInputStreamByUrl(appendixUrl);
                InputStream inputStream = httpURLConnection.getInputStream();
                //取文件名称
                Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                //格式:Content-Disposition: attachment; filename=”fname.ext”
                if (Objects.nonNull(headerFields) && headerFields.containsKey("Content-Disposition")) {
                    List<String> strings = headerFields.get("Content-Disposition");
                    if (!CollectionUtils.isEmpty(strings)) {
                        String oriFileName = strings.iterator().next();
                        // String.indexOf("")判断索引下标从几开始
                        String fileName = oriFileName.substring(oriFileName.indexOf("filename=") + "filename=".length());
                        messageHelper.addAttachment(URLDecoder.decode(fileName, CommonConstant.CHARSET_UTF8), new ByteArrayResource(transInputStream(inputStream)));
                    }
                }
            } finally {
                if (Objects.nonNull(httpURLConnection)) {
                    if (httpURLConnection instanceof HttpURLConnection) {
                        ((HttpURLConnection) httpURLConnection).disconnect();
                    } else {
                        ((HttpsURLConnection) httpURLConnection).disconnect();
                    }
                }
            }
            javaMailSender.send(mimeMessage);
            log.info("1111111111");
        } catch (Exception e) {
            log.error("邮件发送异常: ", e);
            return false;
        }
        return true;
    }

    private URLConnection getInputStreamByUrl(String appendixUrl) throws IOException {
        URL url = new URL(appendixUrl);
        //创建http链接
        URLConnection conn = url.openConnection();
        //设置超时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", UA);
        return conn;
    }

    /**
     * 转换流:需要关闭conn的连接,需要手动转换is
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static byte[] transInputStream(InputStream is) throws IOException {
        //data用于存放循环读取的临时数据
        byte[] data = new byte[2048];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        BufferedInputStream entryStream = new BufferedInputStream(is, 2048);
        int len= 0;
        while ((len = entryStream.read(data, 0, 2048)) != -1) {
            bos.write(data, 0, len);
        }
        entryStream.close();
        bos.close();
        return bos.toByteArray();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值