• JavaMail 发送邮件


    package com;

    import java.util.Date;
    import java.util.Properties;

    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    //以163邮箱为例

    public class Main {

    // 设置邮箱账户
    public static String myEmailAccount = "xxx@163.com";
    // 邮箱密码 注:密码不是邮箱的登录密码,是 授权码
    public static String myEmailPassword = "xxxx";
    // 邮箱 SMTP 协议
    public static String myEmailSMTPHost = "smtp.163.com";
    // 收件人账户
    public static String receiveMailAccount = "xxxx@xxx.com";

    public static void main(String[] args) throws Exception{


    Properties props = new Properties();  //用于连接邮件服务器的参数配置(发送邮件时需要用到)
    props.setProperty("mail.transport.protocal", "smtp"); //加载SMTP协议
    props.setProperty("mail.smtp.host", myEmailSMTPHost);  //验证协议
    props.setProperty("mail.smtp.auth", "true");  //验证为真

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true); //开启Debug 打印信息
    /**  生成一封新邮件 **/
    MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);

    //开启邮件发送
    Transport transport = session.getTransport();
    //确认账户密码
    transport.connect(myEmailAccount, myEmailPassword);
    //发送邮件
    transport.sendMessage(message, message.getAllRecipients());
    //关闭
    transport.close();

    }

    //生成邮件方法

    private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMailAccount) throws Exception{
    //创建邮件对象
    MimeMessage message = new MimeMessage(session);
    //发件人
    message.setFrom(new InternetAddress(sendMail, "xxxxxx", "UTF-8"));
    //TO:收件人 、 CC:抄送人、BCC:密送   
    message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount, "xx", "UTF-8"));
    //邮件主题
    message.setSubject("xxxxx", "UTF-8");
    //邮件内容
    message.setContent("赶快买根雪糕压压热气吧。", "text/html;charset=UTF-8");

    //时间
    message.setSentDate(new Date());
    //保存
    message.saveChanges();
    //返回邮件
    return message;
    }
    }

  • 相关阅读:
    ubuntu安装mysql并修改编码为utf-8
    ubuntu16.04安装jdk1.8
    解决 Can't Connect to MySQL Server on IPAddress (10061) 的问题
    使用开源数据库客户端DBeaver连接DB2数据库
    Windows下使用console线连接思科交换机
    win7安装JDK6
    Python将excel文件从xls转换为xlsx
    Windows使用Gitblit搭建Git服务器
    B树、B-树、B+树、B*树
    必须熟悉的vim快捷键操作
  • 原文地址:https://www.cnblogs.com/zhuangfei/p/7161890.html
Copyright © 2020-2023  润新知