• 发送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

  • 相关阅读:
    一个好用的网站生成工具
    golang sync.Cond 类
    go语言的一些特性
    git 指令如何撤销一次merge
    k8s学习(二)——etcdctl工具的使用
    python numpy array 的一些问题
    (转) Python Generators(生成器)——yield关键字
    shell 括号学习
    zsh
    vim 常用命令总结
  • 原文地址:https://www.cnblogs.com/renjianjun/p/8098785.html
Copyright © 2020-2023  润新知