Java 发送邮件

JavaMail 依赖、发送纯文本与 HTML 邮件、添加附件。

Intermediate
Key Points用 Jakarta Mail(原 JavaMail)通过 SMTP 发信;授权码而非登录密码,端口 465 用 SSL、587 用 STARTTLS。

添加依赖

Since Java 11 JavaMail is not part of the JDK; add jakarta.mail (new coordinates) or javax.mail (legacy). One dependency line in Maven is enough.

Text
<!-- Maven -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

<!-- Gradle -->
implementation 'com.sun.mail:jakarta.mail:2.0.1'

发送一封简单的 E-mail

The steps: configure the SMTP host and auth, build a Session, compose a MimeMessage, then Transport.send. Put the provider's app password where the password goes.

Java
import java.util.Properties;
import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

public class SendMail {
    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.example.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(props);
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress("from@example.com"));
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to@example.com"));
        msg.setSubject("Hello from Java");
        msg.setText("This is a plain text mail.");

        Transport.send(msg, "from@example.com", "your-app-password");
        System.out.println("sent");
    }
}
Output
sent
This needs a real SMTP account — the host and password above are placeholders. Common Chinese providers: smtp.qq.com (QQ Mail), smtp.163.com (163 Mail); enable SMTP in the web UI and generate an app password first.

发送 HTML 邮件

Replace setText with setContent(html, "text/html; charset=UTF-8") to send HTML. For both plain text and HTML, use a MimeMultipart of subtype alternative.

Java
String html = "<h1>Hello</h1><p>This is <b>HTML</b> mail.</p>";

MimeMessage msg = new MimeMessage(session);
msg.setContent(html, "text/html; charset=UTF-8");

System.out.println(html.contains("<b>"));
Output
true

发送带附件的邮件

Attachments use a mixed MimeMultipart: add the body part first, then a MimeBodyPart per file via attachFile. The container holds the body plus the attachments.

Java
MimeMultipart multipart = new MimeMultipart("mixed");

MimeBodyPart text = new MimeBodyPart();
text.setText("see attachment");

MimeBodyPart file = new MimeBodyPart();
file.attachFile("report.pdf");

multipart.addBodyPart(text);
multipart.addBodyPart(file);

msg.setContent(multipart);
System.out.println(multipart.getCount());
Output
2

Friends & Partners