一:普通方式发送

1.导包

        <!--Java MAil 发送邮件API-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- 真正的实现库 -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.1</version>
        </dependency>

2.代码

  • 实例:通过一个已知的163邮箱发送给他人邮件
    public static void main(String[] args) throws MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "SMTP");
        props.setProperty("mail.smtp.host", "smtp.163.com");
        props.setProperty("mail.smtp.port", "25");
        // 指定验证为true
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.timeout", "1000");
        // 验证账号及密码,密码对应邮箱授权码(163密码可行,qq必须授权码)
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("xxxx@163.com", "xxxxx");
            }
        };
        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);
        // 设置发送者
        message.setFrom(new InternetAddress("xxx同上xxx@163.com"));
        // 设置发送方式与接收者
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("xx10086xx@qq.com"));
        // 设置主题
        message.setSubject("邮件发送测试");
        // 设置内容
        message.setContent("Hello!", "text/html;charset=utf-8");

        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }

二:SpringBoot的JavaMailSenderImpl发送

1.在resources下新建mailConfig.properties
mailConfig.properties
#服务器
mailHost=smtp.163.com
#端口号
mailPort=25
#邮箱账号(使用者改成自己的)
mailUsername=xxxxxx@163.com
#邮箱密码(使用者改成自己的)
mailPassword=xxxxx
#时间延迟
mailTimeout=25000
2.新建一个类去读这个配置文件的内容

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Create by yster@foxmail.com 2018/5/28/028 21:00
 */
public class MailConfig {
    private static final String PROPERTIES_DEFAULT = "mailConfig.properties";
    public static String host;
    public static Integer port;
    public static String userName;
    public static String passWord;
    public static String emailForm;
    public static String timeout;
    public static String personal;
    public static Properties properties;
    static{
        init();
    }

    /**
     * 初始化
     */
    private static void init() {
        properties = new Properties();
        try{
            InputStream inputStream = MailConfig.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT);
            properties.load(inputStream);
            inputStream.close();
            host = properties.getProperty("mailHost");
            port = Integer.parseInt(properties.getProperty("mailPort"));
            userName = properties.getProperty("mailUsername");
            passWord = properties.getProperty("mailPassword");
            emailForm = properties.getProperty("mailUsername");
            timeout = properties.getProperty("mailTimeout");
            personal = "来自星星的我";//发送人
        } catch(IOException e){
            e.printStackTrace();
        }
    }
}
3.以上只是准备阶段,下面开始邮件编码

import cn.zyzpp.config.MailConfig;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Create by yster@foxmail.com 2018/5/28/028 21:05
 */
public class MailUtil {
    private static final String HOST = MailConfig.host;
    private static final Integer PORT = MailConfig.port;
    private static final String USERNAME = MailConfig.userName;
    private static final String PASSWORD = MailConfig.passWord;
    private static final String emailForm = MailConfig.emailForm;
    private static final String timeout = MailConfig.timeout;
    private static final String personal = MailConfig.personal;
    private static JavaMailSenderImpl mailSender = createMailSender();
    /**
     * 邮件发送器
     *
     * @return 配置好的工具
     */
    private static JavaMailSenderImpl createMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(HOST);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout", timeout);
        p.setProperty("mail.smtp.auth", "false");
        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 发送邮件
     *
     * @param to 接受人
     * @param subject 主题
     * @param html 发送内容
     * @throws MessagingException 异常
     * @throws UnsupportedEncodingException 异常
     */
    public static void sendMail(String to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 设置utf-8或GBK编码,否则邮件会有乱码
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(emailForm, personal);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        mailSender.send(mimeMessage);
    }
4.开始发送一封邮件
    public static void main(String[] args){
        try {
            MailUtil.sendMail("xxxx@qq.com", "标题", "内容");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

欢迎关注博主!

Java发送Email邮件及SpringBoot集成的更多相关文章

  1. 用java发送email邮件例子

    package com.hzk.mail; import java.net.MalformedURLException; import java.net.URL; import java.text.S ...

  2. java mail Received fatal alert: handshake_failure java 无法发送邮件问题 java 发送qq邮件(含源码)

     java 无法发送邮件问题 java 发送qq邮件 报错:java mail Received fatal alert: handshake_failure (使用ssl) javax.mail.M ...

  3. java发送email一般步骤

    java发送email一般步骤 一.引入javamail的jar包: 二.创建一个测试类,实现将要发送的邮件内容写入到计算机本地,查看是否能够将内容写入: public static void mai ...

  4. Java发送email的端口问题

    Could not connect to SMTP host: smtp.***.com, port: 465, response: -1 使用Java发送email 的端口问题.一般使用25端口即可 ...

  5. C#发送Email邮件(实例:QQ邮箱和Gmail邮箱)

    下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用: using System.Net.Mail; using System.Text; using System.Net; ...

  6. [转]C#发送Email邮件 (实例:QQ邮箱和Gmail邮箱)

    下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用:using System.Net.Mail;using System.Text;using System.Net; 程序 ...

  7. 【转】C#发送Email邮件

    转自:http://hi.baidu.com/bluesky_cn/item/8bb060ace834c53f020a4df2 下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需 ...

  8. java发送email

    package com.assess.util; import java.io.File; import java.util.ArrayList; import java.util.List; imp ...

  9. 【工具】java发送验证码邮件

    文章目录 前言 配置邮箱服务器 代码实现 发送随机验证码与验证 后记 前言 要实现 可以设置格式,附件,抄送等功能,就跟真人操控邮箱发送邮件一样的功能,或许比较难,博主没研究,博主暂时没用到那些功能, ...

随机推荐

  1. 为libevent添加websocket支持(上)

    在跨平台网络基础库中,libevent与asio近年来使用比较广泛.asio对boost的依赖太大,个人认为发展前途堪忧,尤其asio对http没有很好的支持也是缺点之一. libevent对http ...

  2. 如何让python嵌入html实现类似php的快速开发,十分有价值

    1.在一个文件夹名为www.html3.com的web项目来实现,首先到nginx的配置文件nginx.conf做如下配置 python和html混合编写的文件,我以文件后缀为.phtml,通过服务器 ...

  3. mac上Docker安装&初体验

    Docker是什么? Docker是一个虚拟环境容器,可以将你的开发环境.代码.配置文件等一并打包到这个容器中,并发布和应用到任意平台中. 官方文档:https://docs.docker.com H ...

  4. SQL Server 2012还原一直卡在ASYNC_IO_COMPLETION浅析

    在SQL Server 2012(11.0.7001.0)下面在还原一个数据库(备份文件40多G大小,实际数据库大小300G),在还原过程中,出现一直等待ASYNC_IO_COMPLETION,如下测 ...

  5. asp.net core 发布到 docker 容器时文件体积过大及服务端口的配置疑问

    在 asp.net core 发布时,本人先后产生了3个疑问. 1.发布的程序为什么不能在docker容器中运行 当时在window开发环境中发布后,dotnet xxx.dll可以正常运行:但放入d ...

  6. MyBatis笔记----MyBatis 入门经典的两个例子: XML 定义与注解定义

    ----致敬MyBatis官方开放文档让大家翻译,不用看书直接看文档就行了,mybatis的中文文档还需要完备的地方 简介 什么是 MyBatis ? MyBatis 是支持定制化 SQL.存储过程以 ...

  7. Q2Day81

    性能相关 在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢. import requests def fetch_async(url): ...

  8. Python常用的数据类型转换

    在实际开发中.经常要根据需求来转变一些变量的类型. 需要用到以下函数:

  9. VS2017做为Unity3D的脚本编辑器需要的最精简组件

    前言 使用VS2017做为Unity的脚本编辑器,需要的最精简组件. 我的测试环境 windows 10 x64 windows 7 x64 sp1 时间:2017-4-22 更新于2018-12-4 ...

  10. php配置文件php.ini的详细解析

    ;;;;;;;;;;;;;;;;;;;; ; Language Options ; ;;;;;;;;;;;;;;;;;;;; ; Enable the PHP scripting language e ...