使用python中的smtplib将django FileField内容作为电子邮件附件发送?

时间:2012-11-15 08:38:39

标签: python django email smtplib filefield

我想发送带有各种附件的电子邮件。这些附件作为FileField存储在django模型中。我设法创建邮件并发送附件,但附件是空的,而我希望它包含FileField内容。谢谢你的帮助!

def sendEmailHtml(fromaddr, toaddrs, body, subject, attachmentFiles=[]):
    """ Sends HTML email using hardcoded server parameters

    attachmentFiles is a list of FileFields
    """
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = subject
    # Create the body of the message
    html = """\
    <html>
      <head></head>
      <body>
        """+body+"""
      </body>
    </html>
    """
    # Record the MIME types of the parts 
    part1 = MIMEText(html, 'html')
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    # add attachments
    for file in attachmentFiles:       
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(unicode(file.read(), 'utf-8'))
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', 
               filename=file.name)
        msg.attach(part)        

    # Send the message via local SMTP server.
    username = 'example@gmail.com'
    password = 'examplepwd'
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()

我猜以下几行都是错误的,所以我尝试了很多不同的版本,暂时没有成功。我们将非常感谢您的帮助。

        part = MIMEBase('application', 'octet-stream')
        part.set_payload(unicode(file.read(), 'utf-8'))
        Encoders.encode_base64(part)
编辑:我不明白为什么file.read()返回空内容...如果有人能解释,那就太好了。无论如何,这是一个纠正的功能,它起作用:

def sendEmailHtml(fromaddr, toaddrs, body, subject, attachmentFiles=[]):
    """ Sends HTML email using hardcoded server parameters

    attachmentFiles is a list of FileFields
    """
    # Create message container - the correct MIME type is multipart/alternative for alternative
    # formats of the same content. It's related otherwise (e.g., attachments).
    msg = MIMEMultipart('related')
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = subject
    # Create the body of the message (a plain-text and an HTML version).
    # Note: email readers do not support CSS... We have to put everything in line
    html = """\
    <html>
      <head></head>
      <body>
        """+body+"""
      </body>
    </html>
    """
    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(html, 'html')
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    # add attachments
    # for debugging
    debug = False
    if debug:
        # force the presence of a single attachment
        if (len(attachmentFiles)!=1):            
            raise NameError("The number of attachments must be exactly 1, not more, not less.")
        else:
            # print the value of every possible way to obtain the content
            content = "[1] "+unicode(attachmentFiles[0].read(), 'utf-8')
            content += "[2] "+attachmentFiles[0].read()
            content += "[3] "+str(attachmentFiles[0])
            content += "[4] "+open(str(attachmentFiles[0]),'r').read()            
            if (len(content)==0):
                raise NameError("The file to be attached is empty !")
            else:
                # print the content
                raise NameError("Everything ok: content="+content)
                pass
    # end of debugging code
    for file in attachmentFiles:
        format, enc = mimetypes.guess_type(file.name)
        main, sub = format.split('/')
        part = MIMEBase(main, sub)       
        #part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(str(file),'r').read())
        #Encoders.encode_base64(part)
        Encoders.encode_quopri(part)
        part.add_header('Content-Disposition', 'attachment', 
               filename=file.name)
        msg.attach(part)        

    # Send the message via local SMTP server.
    username = 'example@gmail.com'
    password = 'thepassword'
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()

注意:打开后我忘记了关闭指令。

0 个答案:

没有答案