关于java:java实现发送qq邮件

10次阅读

共计 2419 个字符,预计需要花费 7 分钟才能阅读完成。

// 测试邮件

public static void main(String[] args) throws Exception {Properties props = config();
    // 构建受权信息,用于进行 SMTP 进行身份验证
    Authenticator authenticator = new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {
            // 用户名、明码
            String userName = props.getProperty("mail.user");
            String password = props.getProperty("mail.password");
            return new PasswordAuthentication(userName, password);
        }
    };
    // 应用环境属性和受权信息,创立邮件会话
    Session mailSession = Session.getInstance(props, authenticator);
    // 创立邮件音讯
    MimeMessage message = new MimeMessage(mailSession);
    // 设置发件人
    InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
    message.setFrom(form);
    // 设置收件人的邮箱
    List<String> email = new ArrayList<>();
    email.add("***@163.com");
    email.add("***@qq.com");
    InternetAddress[] to_email = new InternetAddress[email.size()];
    for (int i = 0; i < email.size(); i++) {to_email[i] = new InternetAddress(String.valueOf(email.get(i)));
    }
    //InternetAddress to = new InternetAddress(email.size());
    //message.setRecipient(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.TO,to_email);

    // 设置邮件题目
    message.setSubject("====test====");

    // 收件人
    //List<String> email = new ArrayList<>();
    //email.add("**@163.com");
    //message.setRecipients(Message.RecipientType.TO, String.valueOf(email));

    // 设置邮件的内容体
    //message.setContent("新闻联播", "text/html;charset=UTF-8");

    /*MimeBodyPart messageBodyPart =new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    File attachment;
    attachment= new File("E:/video/ 青玉案 - 元夕.txt");
    DataSource fileDataSource=new FileDataSource(attachment);
    messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
    messageBodyPart.setFileName(attachment.getName());
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);*/

    // 文本
    //String content = SendMailUtil.readHtmlContent("E:/video/ 青玉案 - 元夕.txt");
    String content = SendMailUtil.readHtmlContent("E:/video/video02.mp4");
    content = content.replaceAll("\\{\\{title\\}\\}","==============ceshi=================");
    message.setContent(content.toString(),"text/html;charset=UTF-8");
    //message.setText("明月别枝惊鹊,清风中午鸣蝉。稻花香里说歉年,听取蛙声一片。","text/html;charset=UTF-8");
    Transport.send(message);
}

/**
 * 自定义配置
 */
private static Properties config(){Properties props = new Properties();
    // 示意 SMTP 发送邮件,必须进行身份验证
    props.put("mail.smtp.auth", "true");
    // 此处填写 SMTP 服务器
    props.put("mail.smtp.host", "smtp.qq.com");
    // 端口号,QQ 邮箱端口 587
    props.put("mail.smtp.port", "587");
    // 此处填写,写信人的账号
    props.put("mail.user", "***@qq.com");
    // 此处填写 16 位 STMP 口令
    props.put("mail.password", "*****");
    return props;
}
正文完
 0