java 邮件发送图片
时间: 2023-08-30 13:06:54 浏览: 55
要在 Java 中发送带有图片的电子邮件,可以使用 JavaMail API 和 Java Activation Framework(JAF)。
以下是一个简单的示例代码,演示如何发送带有图片的电子邮件:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmailWithImage {
public static void main(String[] args) throws Exception {
// 邮件服务器的属性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.auth", "true");
// 创建一个会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@example.com"));
message.setSubject("Email with Image");
// 创建邮件正文
MimeMultipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("This email contains an image:<br><img src=\"cid:image\">", "text/html");
multipart.addBodyPart(messageBodyPart);
// 创建邮件附件
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("image.jpg");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);
// 将正文和附件添加到邮件中
message.setContent(multipart);
// 发送邮件
Transport.send(message);
}
}
```
在上面的示例中,邮件正文包含一个 HTML 片段,其中包含指向图片的引用。邮件附件使用 `MimeBodyPart` 创建,并将其添加到 `MimeMultipart` 中。附件的 Content-ID 设置为 "image",以便在 HTML 中引用。
请注意,您需要将示例代码中的以下内容替换为您自己的值:
- `smtp.example.com` - 您的邮件服务器主机名
- `username` - 您的邮件服务器用户名
- `password` - 您的邮件服务器密码
- `from@example.com` - 发件人的电子邮件地址
- `to@example.com` - 收件人的电子邮件地址
- `image.jpg` - 包含要添加到电子邮件的图像的文件路径