How to embed Base64 images into e-mail using JavaMail
•
Java
I'm trying to send email from JavaMail using embedded Base64 images (IMG ALT = 'image PNG' SRC = 'data: image / PNG; Base64, ivborw0kgoaaansuheuga... Aelftksuqmcc')
It uses a small image, but when the image is large, the image will not be displayed in the lotus note
This is part of the code
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();`
I want to test it with the precoded mime bodypart, but I don't know how to use it. Can anyone help me:)?
Solution
Well, I found the answer. I don't know I did it right, but it worked normally
This is my code:
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();
}
Thanks for helping me improve. If I need to improve:)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
