我只想在python中发送带附件的电子邮件
import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.login('fu@gmail.com','fu')
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
ATTACHMENTS = ['/tmp/2013-11-04-test.csv']
send_from=['fu@gmail.com']
send_to=['fu@gmail.com']
subject='adfadfadf'
text = 'adfadfadf'
send_mail(send_from, send_to, subject, text, files=ATTACHMENTS)
我如何授权?我必须提供用户名和密码。怎么样?
Traceback (most recent call last):
File "/home/ubuntu/workspace/miliza-devops/classes/utilities.py", line 133, in <module>
send_mail(send_from, send_to, subject, text, files=ATTACHMENTS)
File "/home/ubuntu/workspace/miliza-devops/classes/utilities.py", line 124, in send_mail
smtp.login('fu@gmail.com','fu')
File "/usr/lib/python2.7/smtplib.py", line 576, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
答案 0 :(得分:25)
登录前需要致电starttls()
:
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.starttls()
smtp.login('fu@gmail.com', 'fu')
此外,您的send_from
应该是str
,而不是list
:
send_from='fu@gmail.com'
请注意smtp.starttls()
隐式调用smtp.ehlo()
:
如果此会话没有先前的EHLO或HELO命令,则此方法首先尝试ESMTP EHLO。 https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.starttls
答案 1 :(得分:2)
在Gmail上,您还必须在smtp.ehlo()
之前提供smtp.starttls()
这也是How to send an email with Gmail as provider using Python?