1. ホーム
  2. パイソン

python smtplib TypeError: 期待される文字列またはバッファ

2022-03-16 13:01:55

問題の説明

プレーンテキストのメールを送信し、実行するとエラーを報告するスクリプトを書きました。

[root@server1 test]# python2.7 sender_plain.py
Traceback (most recent call last):
  File "sender_plain.py", line 36, in <module>
    send_mail(send_from, reply_to, send_to, subject, text)
  File "sender_plain.py", line 25, in send_mail
    smtp.sendmail(send_from, reply_to, send_to, msg.as_string())
  File "/usr/local/lib/python2.7/smtplib.py", line 736, in sendmail
    (code, resp) = self.data(msg)
  File "/usr/local/lib/python2.7/smtplib.py", line 499, in data
    q = quotedata(msg)
  File "/usr/local/lib/python2.7/smtplib.py", line 166, in quotedata
    re.sub(r'(? :\r\n|\n|\r(?! \n))', CRLF, data))
  File "/usr/local/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer









sender_plain.pyのコードです。

#coding=utf-8
import smtplib, os
from email.message import Message
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, server="localhost", port=4467):
    assert type(send_to)==list

    # Create MIME and add message headers
    msg = MIMEMultipart()
    msg['To'] = COMMASPACE.join(send_to)
    msg['From']=send_from
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime = 1)
    # Create MIMEText and add to msg
    body = MIMEText(text,_subtype = "plain",_charset="utf-8")
    msg.attach(body)
    print msg.as_string()
    
    smtp = smtplib.SMTP(server,port)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

    
if __name__=="__main__":
    send_from = "[email protected]"
    send_to = ["[email protected]","[email protected]","[email protected]"]
    reply_to = "[email protected]"
    subject = u"Send plain text email with no attachment content"
    text = u"Sending plain text mail with no attachments"
    send_mail(send_from, send_to, subject, text)













Pythonのバグか?

これを読んで、私も"

i can't understand how this simple mistake does not be noticed

"

これはもうpython2.7!!!!

https://mail.python.org/pipermail/python-bugs-list/2010-March/093097.html