JAVAMAIL试用google邮箱发送邮件

这里的Demo简单来,希望给第一次试用的你帮助。
. 1,试用网易邮箱发送邮件:

  //网易
public static Session getNetEasySession() {
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.host", "smtp.163.com");
    props.setProperty("mail.smtp.port", "25");
    props.setProperty("mail.smtp.auth", "true");

    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(FROM, "panda0920");
        }
    });
    return session;
}

. 2,google邮箱发送邮件:

    public static Session getGMailSession() {
    Properties props = new Properties();
//        props.put("mail.smtp.host", "smtp.gmail.com");
//        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.smtp.socketFactory.fallback", "false");
//        props.put("mail.smtp.port", "465");
//        props.put("mail.smtp.socketFactory.port", "465");
//        props.put("mail.smtp.auth", "true");

        //当前用这种方式。
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override  
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, "panda0920");
            }
        });  
        return session;  
    }

来一个main测试下

private static final String FROM = "xxxxxx@gmail.com";

   public static void sendAccountActivateEmail(String email,String vaildCode)throws Exception {
        Session session = getGMailSession();
            MimeMessage message = new MimeMessage(session);
            message.setSubject("test");
            message.setSentDate(new Date());
            message.setFrom(new InternetAddress(FROM));            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
//            message.setContent("test11111",","text/html;charset=utf-8");            // 发送邮件  
            Transport.send(message);
    }
 public  static void  main(String args[]){
        try {           sendAccountActivateEmail("99999999@qq.com","test");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意项:不管是网易还是谷歌邮箱都需要登录邮箱设置安全登录之类的,比如:

这里写图片描述这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值