gpt4 book ai didi

java - 如何使用 javamail 将 base64 图像嵌入到电子邮件中

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:27:02 24 4
gpt4 key购买 nike

我正在尝试从带有嵌入 base64 图像的 javamail 发送电子邮件 (img alt='image PNG' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...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 来测试,但不知道怎么用有人可以帮我 :) 吗?

最佳答案

好的,伙计们,我找到了我的答案,我不知道我是否做对了,但正在工作。

这里是我的代码:

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();
}

感谢帮助我改进,如果需要改进:)

关于java - 如何使用 javamail 将 base64 图像嵌入到电子邮件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21703817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com