java 之QQ邮件发送

安装jar包

  • JavaMail mail.jar 1.4.5
  • JAF(版本 1.1.1) activation.jar

上码

package com.advanced;

// java 邮件发送 
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;

public class SendEmail {

    public static void main(String[] args) {
         String to = "[email protected]"; 
         String from = "[email protected]";
         String host = "smtp.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() { 
            public PasswordAuthentication getPasswordAuthentication() { 
            // 发件人邮件用户名,密码(qq授权码) 
                return new PasswordAuthentication("[email protected]", "pkvjxxxxdec"); 
            } 
        });
        try {
         // 创建默认的 MimeMessage 对象 
         MimeMessage message = new MimeMessage(session);
        // 头部字段设置 
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        // subject 头部字段
         message.setSubject("This is the Subject Line Pardon110!...");
        // 设置消息体 
        message.setText("This is actual message.");
        // 发送消息体 
        Transport.send(message); 
        System.out.println("Sent message successfully....from pardon110.com");
        } catch (MessagingException mex) { 
            mex.printStackTrace(); 
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u011584949/article/details/82227146
今日推荐