Java 发送邮件

import com.sun.mail.util.MailSSLSocketFactory;
import jakarta.activation.DataHandler;
import jakarta.activation.FileDataSource;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;

import java.security.GeneralSecurityException;
import java.util.Properties;

public class Email {
    //qakhntqhjdfxdbgb
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");
        //需要加下面这几句
        MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
        mailSSLSocketFactory.setTrustAllHosts(true);
        properties.put("mail.smtp.sll.enable","true");
        properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("[email protected]","QQ 邮箱授权码");      
            }
        });
        session.setDebug(true);         
        Transport transport = session.getTransport(); 
        transport.connect("smtp.qq.com","[email protected]","QQ 邮箱授权码");
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress("[email protected]"));
        //使用setRecipients可以给多人发送邮件
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));
        mimeMessage.setSubject("测试");
//        mimeMessage.setContent("这是一个java发送邮件的测试","text/html;charset=utf-8");
        //准备图片
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dataHandler = new DataHandler(new FileDataSource("F:\\ceshi\\素材\\demo2181078\\demo2190855\\img\\hhh_logo.png"));
        image.setDataHandler(dataHandler);
        image.setContentID("hhh_logo");         //给图片设置一个id,方便下面调用
        //准备正文
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("

这是一个测试



测试完成","text/html;charset=utf-8"); //描述数据关系 MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(image); mimeMultipart.addBodyPart(text); mimeMultipart.setSubType("related"); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } }

你可能感兴趣的:(QQ邮箱,java)