【问题标题】:Email Sending Python to Java Conversion电子邮件发送 Python 到 Java 的转换
【发布时间】:2014-08-21 17:24:12
【问题描述】:

我在数据库中存储了 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图片字符串并不完整。

请帮忙。

【问题讨论】:

    标签: java python grails base64 html-email


    【解决方案1】:

    这里需要注意两点,multipart 必须设置为 trueinline 图像应该以 byte[]FileInputStreamSource 作为最后一个参数:

    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
    }
    

    【讨论】:

    • 搞定了。采纳为最佳答案!谢谢。
    【解决方案2】:

    根据插件源代码,可能有inline() 调用:

    inline(String fileName, String contentType, byte[] bytes)
    inline(File file)
    inline(String fileName, File file)
    inline(String fileName, String contentType, File file)
    inline(String fileName, String contentType, InputStreamSource source)
    

    所以你应该通过你的byteArray(不是基于它的String)来匹配第一个:

    sendMail {
        from "sender@somedomain.com"
        to "receiver@somedomain.com"
        subject "Report - Sample"
        html htmlStr
        inline 'imageId', 'image/png', byteArray
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      相关资源
      最近更新 更多