Java实现邮件功能

Java实现邮件发送 

public class MailServlet {

    public static void main(String[] args) throws Exception {
        //创建一个配置文件
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");

        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //java发送邮件的步骤

        // 1.创建应该用程序所需要的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //传入发件人的姓名和授权码
                return new PasswordAuthentication("[email protected]","授权码");
            }
        });

        //开启debug模式,可以查看邮件发送情况
        session.setDebug(true);

        // 2.通过Session得到获取连接对象(Transport)
        Transport transport = session.getTransport();

        // 3.使用邮箱的用户名和授权码连接邮件服务器
        transport.connect("smtp.qq.com","[email protected]","授权码");

        // 4.创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("[email protected]"));
        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
        //邮件标题
        mimeMessage.setSubject("冠希哥");
        //邮件内容
        mimeMessage.setContent("最帅","text/html;charset=UTF-8");

        // 5.发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        // 6.关闭连接
        transport.close();

    }
}

Java实现文本图片附件复杂的邮件发送  

public class SendComplexEmail {
    public static void main(String[] args) throws GeneralSecurit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值