java通过qq邮箱账号发送邮件

发布时间 2023-06-07 15:44:48作者: james-roger

  implementation group: 'javax.mail', name: 'mail', version: '1.4.7'

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailSender {
    public static void main(String[] args) {
        // 配置SMTP服务器和账号信息
        String host = "smtp.qq.com";
        int port = 465;
        String username = "your_email@qq.com";
        String password = "your_password";

        // 创建Properties对象,并设置SMTP服务器信息
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");

        // 创建Session对象,需要提供认证信息
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建MimeMessage对象
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
            message.setSubject("Email Subject");

            // 创建邮件正文部分
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText("Email content");

            // 创建附件部分
			MimeBodyPart attachmentPart = new MimeBodyPart();
            String attachmentFileName = MimeUtility.encodeText(attachment.getName()); // 编码附件名称,解决中文乱码问题
            DataSource source = new FileDataSource(attachment);
            attachmentPart.setDataHandler(new DataHandler(source));
            attachmentPart.setFileName(attachmentFileName);

            // 创建多部分邮件
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);

            // 将多部分邮件设置为消息内容
            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);
            System.out.println("Email sent successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}