如何使用javamail将base64图像嵌入电子邮件

xqkwcwgp  于 2023-03-11  发布在  Java
关注(0)|答案(3)|浏览(178)

我正在尝试从javamail发送嵌入base64图像的电子邮件(img alt ='image PNG' src ='data:image/png;碱基64,iV带0KGgoAAAANSUhEUgA...AELFTKSUQmCC“”)
它可以处理小图像,但当图像较大时,图像不会显示在lotus note中。
这里是代码的一部分

Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage( mailSession );
message.setSubject( subject );
message.setFrom( new InternetAddress( me) );
message.setContent( bodyWithEmbeddedBase64Image, "text/html" );
transport.connect();
transport.sendMessage( message, message.getAllRecipients() );
transport.close();`

我想使用PreencodedMimeBodyPart来测试它,但我不知道如何使用它,有人能帮助我吗:)?

avkwfej4

avkwfej41#

好吧,伙计们,我找到了我的答案,我不知道我做得对不对,但正在起作用。
这里我的代码:

private static final Pattern imgRegExp  = Pattern.compile( "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>" );
public send(email) throws Exception{

   Map<String, String> inlineImage = new HashMap<String, String>();
   String body = email.getBody();
   final Matcher matcher = imgRegExp.matcher( body );
   int i = 0;
   while ( matcher.find() ) {
      String src = matcher.group();
      if ( body.indexOf( src ) != -1 ) {
         String srcToken = "src=\"";
         int x = src.indexOf( srcToken );
         int y = src.indexOf( "\"", x + srcToken.length() );
         String srcText = src.substring( x + srcToken.length(), y );
         String cid = "image" + i;
         String newSrc = src.replace( srcText, "cid:" + cid );
         inlineImage.put( cid, srcText.split( "," )[1] );
         body = body.replace( src, newSrc );
         i++;
      }
   }
   Transport transport = mailSession.getTransport();
   MimeMessage message = new MimeMessage( mailSession );
   message.setSubject( email.getObjet() );
   message.setSender( new InternetAddress( email.getSender() ) );
   message.setFrom( new InternetAddress( email.getFrom()) );
   BodyPart bp = new MimeBodyPart();
   bp.setContent( body, "text/html" );
   MimeMultipart mmp = new MimeMultipart();
   mmp.addBodyPart( bp );
   Iterator<Entry<String, String>> it = inlineImage.entrySet().iterator();
   while ( it.hasNext() ) {
      Entry<String, String> pairs = it.next();
      PreencodedMimeBodyPart pmp = new PreencodedMimeBodyPart( "base64" );
      pmp.setHeader( "Content-ID", "<" + pairs.getKey() + ">" );
      pmp.setDisposition( MimeBodyPart.INLINE );
      pmp.setText( pairs.getValue() );
      mmp.addBodyPart( pmp );
   }
   message.setContent( mmp );
   message.addRecipient( Message.RecipientType.TO, new InternetAddress( email.getTo() ) );
   transport.connect();
   transport.sendMessage( message, message.getAllRecipients() );
   transport.close();
}

如果需要改进的话,谢谢你帮助我改进:)

xt0899hw

xt0899hw2#

由于图像不在单独的身体部位中,因此PreencodedMimeBodyPart将无法帮助您。
你怎么用base64编码图像的?
另一种方法是使用多部分/相关消息,其中图像位于单独的部分中,使用cid引用:网址。

ig9co6j1

ig9co6j13#

试试下面!

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

private File getImgFile(String data, String cid) throws IOException {
    String base64Image = data.split(",")[1];
    byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));

    File outputfile = new File(cid);
    ImageIO.write(img, "jpg", outputfile);
    return outputfile;
}

public Message buildMessageWithEmbeddedImage(Session session) throws MessagingException, IOException {
    SMTPMessage m = new SMTPMessage(session);
    MimeMultipart content = new MimeMultipart("related");

    MimeBodyPart textPart = new MimeBodyPart();
    
    String html = "HTML"; //Your HTML having Base64 Encoded Images
    String[] parts = html.split("src=\"");
    
    Map<String, File> map = new HashMap<>();
    String revisedHTML = parts[0];
    for(int i=1; i<parts.length; i++) {
        String img = parts[i].substring(0, parts[i].indexOf("\""));
        String cid = ContentIdGenerator.getContentId();
        File f = getImgFile(img, cid);
        map.put(cid, f);
        revisedHTML+= "src=\"cid:"+cid+"\" "+parts[i].substring(parts[i].indexOf("\""), parts[i].length());
    }
    textPart.setText(revisedHTML, "US-ASCII", "html");
    content.addBodyPart(textPart);
    
    for (String k : map.keySet()) {
        // Image part
        MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.attachFile(map.get(k));
        imagePart.setContentID("<" + k + ">");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        content.addBodyPart(imagePart);
    }

    m.setContent(content);
    m.setSubject("Your Email Subject");
    return m;
}

**注意:**图像文件将创建在您的项目根文件夹中,如果您想在发送电子邮件后删除,您可以删除。但请确保在发送电子邮件后删除。

相关问题