java 发邮件,怎么设置发信人头像
时间: 2023-10-25 12:22:11 浏览: 271
java邮件群发代码
5星 · 资源好评率100%
在 Java 中发送邮件时,可以通过设置邮件头部信息中的 "Content-Type" 和 "Content-Disposition" 字段来添加发件人头像。
示例代码如下:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmailWithAvatar {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_email_password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email@example.com"));
// 设置发件人头像
message.setHeader("Content-Type", "image/jpeg; name=avatar.jpg");
message.setHeader("Content-Disposition", "inline; filename=avatar.jpg");
message.setHeader("Content-Transfer-Encoding", "base64");
message.setContent("<img src='cid:avatar.jpg'/>", "text/html");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient_email@example.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在上述代码中,我们设置了邮件头部信息中的 "Content-Type" 和 "Content-Disposition" 字段,将发件人头像作为邮件的内嵌资源,通过 "cid:avatar.jpg" 的方式在邮件正文中引用。
阅读全文