I'm trying to send email from javamail with embeded base64 image (img alt='image PNG' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...AElFTkSuQmCC'")
It's working with small image but when images are bigger the image doesnt show in lotus note.
Here a 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 would like to use PreencodedMimeBodyPart to test it but I don't know how to use it Can someone help me please :) ?
Ok guys I found my answers, I don't know if I'm doing right, but is working.
Here 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 to help me to improve if it need to be improved :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With