用JavaMail发送邮件,如何在邮件中插入图片
我用JavaMail写了一个发送邮件的程序,但是在本文中嵌入图片的时候,图片却以附件的方式发送到了对方的邮箱里,这是为什么呢?
下面是我的编写的部分代码:
//准备环境
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
session.setDebug(true);
//创建复杂邮件,中文需要转码
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText("黄金") + "\" <hj350653546@163.com>"));
msg.setSubject("一封复杂邮件");
Multipart mp = new MimeMultipart("mixed");
msg.setContent(mp);
BodyPart content = new MimeBodyPart(); //正文
mp.addBodyPart(content);
Multipart bodyMultipart = new MimeMultipart("related");
content.setContent(bodyMultipart);
BodyPart htmlPart = new MimeBodyPart();
BodyPart gifPart = new MimeBodyPart();
bodyMultipart.addBodyPart(htmlPart);
bodyMultipart.addBodyPart(gifPart);
DataSource gifDs = new FileDataSource(new File("...hj.jpg"));
DataHandler gifDh = new DataHandler(gifDs);
gifPart.setDataHandler(gifDh);
gifPart.setHeader("Content-Location", "http://www.baidu.com/hj.gif");
htmlPart.setContent("<font color=\"red\">这是一封由Java程序自动生成的邮件,请勿回复!</font><img src='http://www.baidu.com/hj.gif' />",
"text/html;charset=GBK");
msg.saveChanges();
//发送邮件
Transport transport = session.getTransport();
transport.connect("smtp.163.com", 25, "帐号", "密码");
transport.sendMessage(msg, InternetAddress.parse("350653546@qq.com"));
transport.close();
------解决方案--------------------
htmlPart.setContent(" <font color=\"red\">这是一封由Java程序自动生成的邮件,请勿回复! </font> <img src='http://www.baidu.com/hj.gif' />",
"text/html;charset=GBK");
你这里不是已经可以显示图片了吗?
BodyPart gifPart = new MimeBodyPart();
DataSource gifDs = new FileDataSource(new File("...hj.jpg"));
DataHandler gifDh = new DataHandler(gifDs);
gifPart.setDataHandler(gifDh);
gifPart.setHeader("Content-Location", "http://www.baidu.com/hj.gif");
这样就是附件了啊