• 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();
        }
    }
    

    }

  • 相关阅读:
    解析Javascript事件冒泡机制
    LeetCode——Flatten Binary Tree to Linked List
    流动python
    HDU2586
    Cannot find ActionMappings or ActionFormBeans collection
    reactor设计模式
    简单的Ajax应用实例
    CString——Left、Right、Find、ReverseFind
    MATLAB新手教程
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/pangb/p/10954910.html
Copyright © 2020-2023  润新知