web基础---->java邮件的发送

  这里记录一下关于java邮件发送代码的编写。你在我身边也好,在天边也罢,想到世界的角落有一个你,觉得整个世界也变得温柔安定了。

java邮件的发送

一、直接贴出代码,如下:

package com.chenhui.huhx.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件的工具类
 * 
 * @author huhx
 * @date: 2016年12月19日 下午4:19:30
 */
public class SendMailUtils {
    public final static String EMAIL_SEND_FROM = "XXX@qq.com"; // 发送方的qq邮箱

    // 发送短信
    public static void sendMail(String to, String message) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", 465); // 这个需要
        props.put("mail.smtp.auth", "true");
        props.put("mail.from", EMAIL_SEND_FROM);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session session = Session.getInstance(props, auth);
        MimeMessage msg = new MimeMessage(session);
        Address address;
        try {
            address = new InternetAddress(EMAIL_SEND_FROM);
            msg.setFrom(address);
            msg.setRecipients(Message.RecipientType.TO, to);
            msg.setSubject("HelloWorld");
            msg.setSentDate(new Date());
            String html = "<html><body><span>" + message + "</span></body></html>";
            msg.setText(html, "utf-8", "html");
            Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送邮件需要授权
    static Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EMAIL_SEND_FROM, "XXXX"); // 这里的XXXX表示授权码
        }
    };
    
    // 测试
    public static void main(String[] args) {
        sendMail("XXXX@qq.com", "我爱你!"); // XXXXX表示接收方的邮箱
    }
}

关于授权码的获得,如下图生成授权码 。

二、对于qq邮箱,需要做一些设置。如下

帐户

友情链接

原文地址:https://www.cnblogs.com/huhx/p/basewebusesendmail.html