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 = "[email protected]";

   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("[email protected]","test");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章