300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java发送图片邮件_使用javamail发送包含图片的html格式邮件详解

java发送图片邮件_使用javamail发送包含图片的html格式邮件详解

时间:2022-12-02 15:39:07

相关推荐

java发送图片邮件_使用javamail发送包含图片的html格式邮件详解

使用JavaMail可以很方便的发送html格式的邮件,只需要将content-type设置为"text/html"即可。要在邮件中包含图片简单办法是使用image标签,src指向服务器上图片的位置。但是有些邮件客户端会把是否包含有服务器端图片作为垃圾邮件的判断机制。我们可以将图片内嵌到邮件中,然后用cid加content-id引用内嵌的图片。

import javax.mail.*;

import javax.mail.internet.*;

import javax.activation.*;

import java.util.Properties;

class SimpleMail2 {

public static void main(String[] args) throws Exception{

System.out.println("Sending mail...");

Properties props = new Properties();

props.setProperty("mail.transport.protocol", "smtp");

props.setProperty("mail.host", "");

props.setProperty("mail.user", "myuser");

props.setProperty("mail.password", "mypwd");

Session mailSession = Session.getDefaultInstance(props, null);

mailSession.setDebug(true);

Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);

message.setSubject("HTML mail with images");

message.setFrom(new InternetAddress("[emailprotected]"));

message.addRecipient(Message.RecipientType.TO,

new InternetAddress("[emailprotected]"));

//

// This HTML mail have to 2 part, the BODY and the embedded image

//

MimeMultipart multipart = new MimeMultipart("related");

// first part (the html)

BodyPart messageBodyPart = new MimeBodyPart();

String htmlText = "

Hello

";

messageBodyPart.setContent(htmlText, "text/html");

// add it

multipart.addBodyPart(messageBodyPart);

// second part (the image)

messageBodyPart = new MimeBodyPart();

DataSource fds = new FileDataSource

("C:\\images\\jht.gif");

messageBodyPart.setDataHandler(new DataHandler(fds));

messageBodyPart.setHeader("Content-ID","");

// add it

multipart.addBodyPart(messageBodyPart);

// put everything together

message.setContent(multipart);

transport.connect();

transport.sendMessage(message,

message.getRecipients(Message.RecipientType.TO));

transport.close();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。