java发送内嵌图片邮件
时间: 2023-07-25 19:03:42 浏览: 58
要在Java中发送内嵌图片邮件,可以使用JavaMail API。以下是一个简单的示例代码:
```java
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.util.Properties;
public class SendInlineImagesEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "recipient@example.com";
// Sender's email ID needs to be mentioned
String from = "sender@example.com";
// Sender's email password needs to be mentioned
String password = "password";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "image.jpg";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(MimeUtility.encodeText(filename));
messageBodyPart.setHeader("Content-ID", "<image>");
// Add part two to multipart
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException | UnsupportedEncodingException mex) {
mex.printStackTrace();
}
}
}
```
在这个示例代码中,我们使用了两个 `MimeBodyPart` 对象来设置邮件正文和内嵌图片。我们在第二个 `MimeBodyPart` 中设置了图片的文件名和 Content-ID,Content-ID 的值可以在 HTML 中使用,来引用这个内嵌图片。在 HTML 中,内嵌图片的格式如下:
```html
<img src="cid:image" alt="image"/>
```
注意,在发送邮件时,需要使用正确的邮箱账号和密码,并且要将 `host` 属性设置为正确的 SMTP 服务器地址。