我正在尝试使用嵌入式base64图像从javamail发送电子邮件(img alt ='image PNG'src ='data:image / png; base64,iVBORw0KGgoAAAANSUhEUgA ... AElFTkSuQmCC'“)
它使用的是小图像,但是当图像较大时,图像不会显示在莲花笔记中。
这是代码的一部分
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测试它,但我不知道如何使用它 请有人帮帮我:)?
答案 0 :(得分:6)
好的我找到了答案,我不知道我做得对,但是有效。
这是我的代码:
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();
}
感谢帮助我改进,如果需要改进的话:)
答案 1 :(得分:1)
由于图像不在单独的身体部位,PreencodedMimeBodyPart不会帮助您。
你如何对图像进行base64编码?
另一种方法是使用多部分/相关消息,将图像放在单独的部分中,使用cid:URL引用。