【问题标题】:Attachment Image to send by mail using Python [duplicate]使用Python通过邮件发送的附件图像[重复]
【发布时间】:2012-10-15 17:20:02
【问题描述】:

可能重复:
How to send Email Attachments with python

我已经使用 Python 对 sendEmail 做了一些工作,我得到了这段代码

import smtplib
def SendAnEmail( usr, psw, fromaddr, toaddr):
    # SMTP server
    server=smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(usr,psw)
    # Send 
    msg="text message ....... "

    server.sendmail(fromaddr, toaddr, msg)
    server.quit()
if __name__ == '__main__':
    # Fill info...
    usr='example@sender.ex'
    psw='password'
    fromaddr= usr
    toaddr='example@recevier.ex'
    SendAnEmail( usr, psw, fromaddr, toaddr)

如果我需要添加图像(附加图像)怎么办?有人知道吗?

【问题讨论】:

    标签: python smtp


    【解决方案1】:
    import os
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    
    
    def SendMail(ImgFileName):
        with open(ImgFileName, 'rb') as f:
            img_data = f.read()
    
        msg = MIMEMultipart()
        msg['Subject'] = 'subject'
        msg['From'] = 'e@mail.cc'
        msg['To'] = 'e@mail.cc'
    
        text = MIMEText("test")
        msg.attach(text)
        image = MIMEImage(img_data, name=os.path.basename(ImgFileName))
        msg.attach(image)
    
        s = smtplib.SMTP(Server, Port)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(UserName, UserPassword)
        s.sendmail(From, To, msg.as_string())
        s.quit()
    

    【讨论】:

      【解决方案2】:

      阅读文档。 smtpblib 文档的最后几行内容如下:

      注意 一般情况下,您会希望使用电子邮件包的功能来构建电子邮件消息,然后您可以将其转换为字符串并通过 sendmail() 发送;请参阅电子邮件:示例。

      并将您指向:https://docs.python.org/3/library/email.examples.html

      这有一个确切的例子。

      【讨论】:

      • 我使用这些行来加载它但不能工作:msg = MIMEMultipart() msg​​.attach(MIMEImage(file('linechart.png').read()))
      • 截至2018-05-17,该文档链接已损坏。 2.7 Examples3.6 Examples 似乎是最新的。请包含代码,而不是仅链接到代码。
      猜你喜欢
      • 2022-08-18
      • 2011-01-09
      • 2013-12-01
      • 1970-01-01
      • 2019-01-22
      • 2013-06-22
      • 1970-01-01
      • 2022-11-14
      • 2018-09-20
      相关资源
      最近更新 更多