zoukankan      html  css  js  c++  java
  • 发送email


    package
    com.rjj.d; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory; public class MailTest2 { //授权码认证 static Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //发送者邮箱和授权码 return new PasswordAuthentication("215060580@qq.com", "xxxxxxxxx");//这里是授权码 } }; public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.qq.com");//这里是SMTP发送服务器的名字 qq的smtp.qq.com props.put("mail.smtp.auth", "true");//smtp是否需要认证 props.put("mail.from", "215060580@qq.com");//发送者的邮箱
         /*
          qq需要些ssl加密否会报错 
           javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl).
           More information at http://service.mail.qq.com/cgi-bin/help?id=28
         */
        //qq邮箱需要设置ssl加密,
    try {
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.enable", "true");
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            //实例化session
            Session session = Session.getInstance(props, auth);
            try {
                // 创建默认的 MimeMessage 对象
                MimeMessage msg = new MimeMessage(session);
                //设置头部字段
                msg.setFrom(new InternetAddress("215060580@qq.com"));//如果写必须写的和发件人邮箱一样
               // msg.setFrom();//可以不写,默认
                msg.setRecipients(Message.RecipientType.TO, "253481340@qq.com");//收件人
                msg.setSubject("JavaMail hello world example");//收到邮件的标题
                msg.setSentDate(new Date());//时间
                msg.setText("Hello, world!
    ");//邮件的身体内容,就是发送的邮件内容
                Transport.send(msg);
            } catch (MessagingException ex) {
                System.out.println("send failed, exception: " + ex);
            }
     
        }
    }

    以上是代码,复制直接可以用,但是需要在qq里边设置开启一些东西

    1.

       qq又想找找到设置,打开这个界面,点击用户,然后往下翻找到

    开启标记的两个服务,并且需要拿到授权码,  点击生成授权码,

    我的设置了手机令牌,会出现这个,填完动态码,会出现

    这个,把授权码赋值到代码中替换xxxxxxxx就行。完了直接运行代码就会个指定的邮箱发送邮件

    这个就是最简单的发送邮件,学习中....

    最后就是jar

  • 相关阅读:
    laytpl模板——怎么使用ajax与数据交互
    项目中遇到的几个日期转换的场景
    input可以自动换行吗???
    EL表达式 if 和 if else语句的写法
    小程序开发之背景图片的设置
    主流浏览器内核
    HTTP状态码
    (四)js数组方法一
    (效果二)js实现两个变量值的交换
    (十八)js控制台方法
  • 原文地址:https://www.cnblogs.com/renjianjun/p/8098785.html
Copyright © 2011-2022 走看看