问题描述
server.send_message(user_name,to,message,subject=subject)
TypeError: send_message() got an unexpected keyword argument 'subject'
此代码
import smtplib
user_name = 'my@gmail.com'
password = '*******'
to = ['my@gmail.com','other_email@gmail.com']
subject = 'Theme'
message = 'Test message'
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login(user_name,password)
server.send_message(user_name,subject=subject)
server.close()
File "C:\\lib\smtplib.py",line 939,in send_message
resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'
我该如何解决这个问题?
编辑:
我找到了方法
import smtplib
gmail_user = 'my_gmail@gmail.com' #like boris273@gmail.com
gmail_password = 'password'
sent_from = gmail_user
to = ['email@gmail.com','email@gmail.com'] #Some emails to which your message will be sent
subject = input('Subject > ')
body = input('Message > ')
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from,",".join(to),subject,body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login(gmail_user,gmail_password)
server.sendmail(sent_from,email_text)
server.close()
print('Email sent!')
except:
print('Something went wrong...')
现在使用 sendmail 而不是 send_message 编码
解决方法
您需要使用 sendmail()
而不是 send_message()
import smtplib
user_name = 'my@gmail.com'
password = '*******'
to = ['my@gmail.com','other_email@gmail.com']
subject = 'Theme'
message = 'Test message'
email_message = 'Subject: {}\n\n{}'.format(subject,message)
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login(user_name,password)
server.send_message(user_name,to,email_message)
server.close()
参考: