2012-03-30 17 views
1

私は、Javaプログラムによって画像をメールに送信する方法について知りたいと思います。 次はどの私はいずれかが知っていれば教えてください画像を添付しないでJavaプログラムでメールに送る?

// 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. 
... 

を使用している...私はそれが私のテキストの過去として来るべきではないしたい ..私は、テキストや画像を送信することができますが、それは添付ファイルとして表示されます。 。副

答えて

4

おかげで、あなたがやっていることのすべては、私はGmailのを使用していると私は、電子メールで画像を確認するために、「表示画像」をクリックして、あなたは画像を参照するには、以下の行を追加することができる必要がある、正しいです:

mbp2.setFileName("image.png"); 

私の完全なコードは次のようになります。

// 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メッセージの本文はこれです:

bodyText = "<p><img style='float:right' src='cid:image_cid'>Hello World example</p>"; 
関連する問題