How to embed base64 image to an email using javamail
我正在尝试使用嵌入的base64图像从javamail发送电子邮件(img alt='image png'src='data:image/png;base64,ivborw0kgoaansuheuga…aelftksuqmcc')
它使用的是小图像,但是当图像更大时,图像不会显示在LotusNote中。
这里是代码的一部分
1 2 3 4 5 6 7 8 | 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();` |
我想用预先编码的mimebodypart来测试它,但我不知道如何使用它有人能帮我一下吗:)
好的,伙计们,我找到了我的答案,我不知道我是否做得对,但我在工作。
这里是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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(); } |
感谢您帮助我改进,如果需要改进的话:)
因为图像不在单独的身体部分,所以预先编码的mimebodypart对您没有帮助。
你是如何对图像进行base64编码的?
另一种方法是使用多部分/相关消息,图像位于单独的部分,使用cid:url引用。