一:普通方式发送

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. leetcode-67.二进制求和

    leetcode-67.二进制求和 Points 数组 数学 题意 给定两个二进制字符串,返回他们的和(用二进制表示). 输入为非空字符串且只包含数字 1 和 0. 示例 1: 输入: a = &qu ...

  2. javascript的函数、事件

    本文内容: 函数 函数的定义方式 函数的调用方式 函数的参数 匿名函数 函数中的this 事件 常见事件 绑定事件 首发日期:2018-05-11 函数: 函数的定义方式: 函数可以有参数,参数为局部 ...

  3. LeetCode题解之Sum Root to Leaf Numbers

    1.题目描述 2.问题分析 记录所有路径上的值,然后转换为int求和. 3.代码 vector<string> s; int sumNumbers(TreeNode* root) { tr ...

  4. 在安卓手机上通过虚拟机运行Windows XP

    转自:https://www.ithome.com/html/android/302170.htm 细数当年的桌面版Windows,似乎针对ARM架构处理器的版本并不多,小编曾用过一段时间的Windo ...

  5. ElementUI在IE11下兼容性修改

    1.在项目里面使用了axios.js来发送http请求,在IE下报错Promise未定义,解决办法: 到http://bluebirdjs.com/docs/getting-started.html  ...

  6. MySQL数据库有哪些安全相关的参数需要修改?

    https://dev.mysql.com/doc/refman/5.7/en/security-options.htmlhttps://dev.mysql.com/doc/refman/5.7/en ...

  7. 聚类——GAKFCM的matlab程序

    聚类——GAKFCM的matlab程序 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 在聚类——GAKFCM文章中已介绍了GAKFCM算法的理论知识, ...

  8. spring的基于XML方式的属性注入

    1.掌握spring的属性注入的方法: 1.1构造方法注入普通值---------<constructor-arg>标签的使用 首先新建一个类 package spring.day1.de ...

  9. Teradata的profile使用

    1.proflie优势 使用profile可以批量管理用户参数,尤其是在一批用户具有相同的参数配置时,十分便捷. 2.profile可配置用户参数 [Account id][Default datab ...

  10. 2883 -- 【TJOI2018】游园会

    Description 小豆参加了\(NOI\)的游园会,会场上每完成一个项目就会获得一个奖章,奖章只会是\(N,O,I\)的字样.在会场.上他收集到了\(K\)个奖章组成的串.兑奖规则是奖章串和兑奖 ...