zoukankan      html  css  js  c++  java
  • Java Email 发送

    需要导入这两个jar包:

    javax.activation
    activation
    1.1.1



    javax.mail
    mail
    1.4.7

    代码:
    public class SendMailUtil {
    public static void main(String[] args) {
    // 收件人电子邮箱
    String to = "pangbin0502@qq.com";

        // 发件人电子邮箱
        String from = "pangbin0502@163.com";
    
        // 指定发送邮件的主机为 smtp.qq.com
        //163 邮件服务器
        String host = "smtp.163.com";
        //收件人(多个)
        String[] TOS = new String[]{"pangbin0502@qq.com"};
    
        // 获取系统属性
        Properties properties = System.getProperties();
    
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
    
        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("pangbin0502@163.com", "163授权码");
            }
        });
    
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
    
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
    
            // Set To: 头部头字段
            /*message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));*/
    
            // 加载收件人地址
            InternetAddress[] sendTo = new InternetAddress[TOS.length];
            for (int i = 0; i < TOS.length; i++) {
                sendTo[i] = new InternetAddress(TOS[i]);
            }
            message.addRecipients(Message.RecipientType.TO, sendTo);
            //为防止5开头报错,先给自己发一份
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from));
    
            // Set Subject: 头部头字段
            message.setSubject("This is the Subject Line!");
    
            // 设置消息体
            message.setText("This is actual message");
    
            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....from runoob.com");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
    

    }

  • 相关阅读:
    C++矢量图形库系列(转)
    ArcGIS Server 地图发布请求分析
    Git在提交代码时出现的fatal: Authentication failed的问题
    创建WPF项目
    Linux查看日志常用命令(转载)
    CentOS6 + MapServer7.4编译
    升级GCC
    QT+OpenGL(03)--libpng库的编译
    QT+OpenGL(02)-- zlib库的编译
    QT+OpenGL(01)--实现三角形渲染
  • 原文地址:https://www.cnblogs.com/pangb/p/10954910.html
Copyright © 2011-2022 走看看