通过java程序发送图像到邮件而不附加? [英] sending image to mail by java program without attaching?
本文介绍了通过java程序发送图像到邮件而不附加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何通过java程序将图像发送到邮件。我可以发送文本和图像,但它显示为附件..
i希望它应该作为我的文本的过去...
以下是我使用的
i would like to know about how to send images to mail by java program. i can send text and images but it displays as attached file.. i want it should come as past of my text... the following is which i used
// Create new message with mail session.
Message message = new MimeMessage(session);
// Create multipart message.
MimeMultipart multipart = new MimeMultipart();
// Create bodypart.
BodyPart bodyPart = new MimeBodyPart();
// Create the HTML with link to image CID.
// Prefix the link with "cid:".
String str = "<html><h1>Hello</h1>" +
"<img src=\"cid:image_cid\"></html>";
// Set the MIME-type to HTML.
bodyPart.setContent(str, "text/html");
// Add the HTML bodypart to the multipart.
multipart.addBodyPart(bodyPart);
// Create another bodypart to include the image attachment.
bodyPart = new MimeBodyPart();
// Read image from file system.
DataSource ds = new FileDataSource("C:\\images\\image.png");
bodyPart.setDataHandler(new DataHandler(ds));
// Set the content-ID of the image attachment.
// Enclose the image CID with the lesser and greater signs.
bodyPart.setHeader("Content-ID", "<image_cid>");
// Add image attachment to multipart.
multipart.addBodyPart(bodyPart);
// Add multipart content to message.
message.setContent(multipart);
// Now set the header and send the email.
...
如果有人知道,请告诉我..
please tell me if any one knows..
感谢adv
推荐答案
你所做的一切都是正确的,我正在使用gmail和我需要点击显示图片查看电子邮件中的图片,你可以添加以下行来查看图片:
All what you are doing is correct, I'm using gmail and I need click on "Display Images" to see images in emails, you can add following line to see image:
mbp2.setFileName("image.png");
我的完整代码如下所示:
My full code looks as this:
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setRecipients(Message.RecipientType.TO, to);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(bodyText, "text/html");
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
DataSource source = new FileDataSource(new File("image.png"));
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName("image.png");
mbp2.setHeader("Content-ID", "<image_cid>"); // cid:image_cid
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// send the message
Transport.send(msg);
和html消息正文如下:
and html message body is this:
bodyText = "<p><img style='float:right' src='cid:image_cid'>Hello World example</p>";
这篇关于通过java程序发送图像到邮件而不附加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文