我将 Base64 编码的图像存储在数据库中。我想生成带有此 base64 图像作为正文内嵌图像的电子邮件。 我尝试将图像发送为
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAooA....'/>
但是我的接收电子邮件服务器正在将包含 Base64 内容的电子邮件正文视为垃圾邮件。但我能够用 python 解决这个问题。用于相同目的的代码是
msg = MIMEMultipart()
msg['Subject'] = Header(u'Subject', 'utf-8')
msg['From'] = sender
msg['To'] = receiver
msg_alternative = MIMEMultipart('alternative')
msg.attach(msg_alternative)
data = 'Hi, <img src="cid:imageId" alt="alternate text"><br><br>'
decodedImage = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAooA....")
msg_image = MIMEImage(decodedImage, name="image")
msg_image.add_header('Content-ID', '<imageId>')
msg_image.add_header('Content-Disposition', 'inline')
msg.attach(msg_image)
使用上面的代码,我能够使用 python 中的 sendmail 模块成功地发送带有内联图像的电子邮件。
但我想要的是使用 grails 电子邮件插件来实现相同的目的。 这个堆栈溢出 URL 帮助我开始了。 Send an image in an email with Grails
但我走错地方了。我使用的代码如下。
String base64String = "iVBORw0KGgoAAAANSUhEUgAAAooA....";
byte[] byteArray = Base64.decodeBase64(base64String.getBytes());
String decodedString = new String(byteArray);
String htmlStr = 'Hi, <img src="cid:imageId" alt="alternate text"><br><br>';
sendMail {
from "sender@somedomain.com"
to "receiver@somedomain.com"
subject "Report - Sample"
html htmlStr
inline 'imageId', 'image/png', decodedString
}
但它显示了一些错误,例如“没有内联匹配的属性..”。 但我认为问题出在参数值decodedString 和内联属性上。
注意:我使用的base64图像字符串不是完整的。
请帮忙。
最佳答案
这里需要注意两件事,multipart
必须设置为 true
且 inline
图像应采用 byte[]
或 File
或 InputStreamSource
作为最后一个参数:
sendMail {
multipart true //has to be there as first line
from "sender@somedomain.com"
to "receiver@somedomain.com"
subject "Report - Sample"
html htmlStr
//Use raw byte array instead of string
inline 'imageId', 'image/png', byteArray
}
关于java - 电子邮件发送 Python 到 Java 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25432317/