1

我想发送带有各种附件的电子邮件。这些附件作为 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()

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

4

0 回答 0