Errno 90发送电子邮件时消息太长

时间:2016-06-03 14:22:34

标签: python django python-2.7 errno

我正在尝试使用python发送带附件的电子邮件,但是因为跟随错误而失败:

2016-06-03 17:10:09,527 - sbo_cloud.documents.views - send_mail|10324 - ERROR - Traceback (most recent call last):
      File "/home/project/django/sbo_cloud/documents/views.py", line 10285, in send_mail
        send_email(user, company, to_addr, subject, message, from_mail=from_addr, cc=cc_addr, bcc=bcc_addr, is_attachment=is_attachment, files_to_attach=pdf_file_dict, notify_sender=notify_sender)
      File "/home/project/django/sbo_cloud/core/utils.py", line 1989, in send_email
        server.sendmail(msg['From'], to_addrs, msg.as_string())
      File "/usr/lib/python2.7/smtplib.py", line 736, in sendmail
        (code, resp) = self.data(msg)
      File "/usr/lib/python2.7/smtplib.py", line 503, in data
        self.send(q)
      File "/usr/lib/python2.7/smtplib.py", line 320, in send
        print>>stderr, 'send:', repr(str)
    IOError: [Errno 90] Message too long

为什么会发生这种情况以及为什么在所有服务器上都没有发生这种情况,它发生在其中两个但不是第三个,使用相同的数据?服务器正在运行ubuntu 14.这个python或服务器是否相关,如何避免?

编辑:

以下是我发送电子邮件的代码:

def send_email(user, company, to_mail, subject, message, is_attachment=False, files_to_attach={}, **kwargs):
# def send_email(company, to_mail, subject, message, **kwargs):
    """
    sends an email, kwargs can be from_mail, cc and bcc lists, subject, message_text and message_html
    This method is used for the company sending an email, not for the program
    is_attachment will be true when file should be attached.
    files_to_attach is a dictionaty whose key is filename and object corresponding to key is fileobject
    that needs to be attached.
    """
    config = EmailConfig(user=user, company=company)

    # from_mail = kwargs.get('from_mail', config.from_address)
    from_mail = config.username

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            message.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(from_mail)
    recipient_name, recipient_addr = parseaddr(to_mail)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    from_alias_addr, from_addr = parseaddr(kwargs.get('from_mail', ''))
    sender_name = str(Header(unicode(from_alias_addr), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    msg = MIMEMultipart('alternative')
    # Create the body of the message (a plain-text and an HTML version).
    # html = kwargs.get('message_html', message)
    # Record the MIME types of both parts - text/plain and text/html.
    # Create the message ('plain' stands for Content-Type: text/plain)
    part1 = MIMEText(message.encode(body_charset), 'plain', body_charset)
    html_message = "<br />".join(message.split("\n"))
    part2 = MIMEText(html_message.encode(body_charset), 'html', body_charset)
    # 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)
    msg.attach(part2)
    try:
        if is_attachment == True:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
            for file_name, file_to_attach in files_to_attach.iteritems() :
                file_format, enc = guess_type(file_name)
                main, sub = file_format.split('/')
                part3 = MIMEBase(main, sub)
# #                part3 = MIMEBase('application', "octet-stream")
                part3.set_payload(file_to_attach.read())
                Encoders.encode_base64(part3)
                part3.add_header('Content-Disposition', 'attachment; filename="%s"' % file_name)
                msg.attach(part3)
    except Exception as e:
        print e

    from_username = formataddr((from_alias_addr, from_addr))
    if email_re.search(from_username):
        msg['From'] = from_username
    else:  # adresa email introdusa invalida, se foloseste cea de la configurare
        msg['From'] = formataddr((sender_name, sender_addr))

    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)
    msg['X-Priority'] = '1'
    msg['X-MSMail-Priority'] = 'High'
    msg['Importance'] = 'High'
    msg['Date'] = formatdate(localtime=True)

    if kwargs.get('notify_sender', False):
        msg['Disposition-Notification-To'] = formataddr((sender_name, sender_addr))
        msg['Return-Receipt-To'] = formataddr((sender_name, sender_addr))

    # Create message container - the correct MIME type is multipart/alternative.
    # cc (and bcc) must be a string of emails (can contain user name) sepparated by coma "addr1@webbi.ro, addr2@webbi.ro"
    cc = kwargs.get('cc', config.cc)
    bcc = kwargs.get('bcc', config.bcc)
    cc_addrs, bcc_addrs = [], []
    if cc:
        for addr in cc.split(','):
            cc_name, cc_addr = parseaddr(addr)
            cc_name = str(Header(unicode(cc_name), header_charset))
            cc_addr = cc_addr.encode('ascii')
            cc_addrs.append(formataddr((cc_name, cc_addr)))
    if bcc:
        for addr in bcc.split(','):
            bcc_name, bcc_addr = parseaddr(addr)
            bcc_name = str(Header(unicode(bcc_name), header_charset))
            bcc_addr = bcc_addr.encode('ascii')
            bcc_addrs.append(formataddr((bcc_name, bcc_addr)))

    return_path = kwargs.get('return_path', None)
    if return_path:
        msg['reply-to'] = return_path

    if cc != "":
        msg['Cc'] = cc
    if bcc != "":
        msg['Bcc'] = bcc
    to_addrs = [msg['To']] + cc_addrs + bcc_addrs

    return_path = kwargs.get('return_path', None)
    if return_path:
        msg['reply-to'] = return_path

    if not config.ssl:
        try:
            with_ssl = False
            server = smtplib.SMTP(config.server_address, int(config.port), timeout=45)  # timeout=45
        except SMTPServerDisconnected:
            with_ssl = True
            server = smtplib.SMTP_SSL(config.server_address, int(config.port), timeout=45)  # timeout=45
            config.ssl = True
    else:
        try:
            with_ssl = True
            server = smtplib.SMTP_SSL(config.server_address, int(config.port), timeout=45)  # timeout=45
        except SMTPServerDisconnected:
            with_ssl = False
            server = smtplib.SMTP(config.server_address, int(config.port), timeout=45)  # timeout=45
            config.ssl = False
    server.set_debuglevel(settings.DEBUG)
    encryptor = SBAESCrypt()
    password = encryptor.decrypt(config.password)
    if not with_ssl and config.tls:
        server.starttls()
    server.login(config.username, password)
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    server.sendmail(msg['From'], to_addrs, msg.as_string())
    server.quit()

    config.save()

由于

0 个答案:

没有答案