我试图在python中创建一个电子邮件脚本。这就是我所拥有的(来自pythonlibrary.org):
#! /usr/bin/env python
import smtplib
import string
SUBJECT = "An email!"
TO = "me@icloud.com"
FROM = "me@gmail.com"
text = "This text is the contents of an email!"
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com')
server.login('me@gmail.com', 'mypassword') # Not very secure, I know, but this email is dedicated to this script
server.sendmail(FROM, [TO], BODY)
server.quit()
我得到smtplib.SMTPException: SMTP AUTH extension not supported by server.
是这样的,为什么smtp.gmail.com会响应呢?这是Gmail,我的脚本或其他什么问题吗?
错误讯息:
Traceback (most recent call last):
File "/Users/student/Desktop/mail.py", line 18, in <module>
server.login('*******@gmail.com', '**************')
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 552, in login
smtplib.SMTPException: SMTP AUTH extension not supported by server.
答案 0 :(得分:7)
您需要在提交端口(587)上联系gmail邮件服务器,而不是默认的25:
server = smtplib.SMTP('smtp.gmail.com', 587)
您还需要在登录前使用server.starttls()
(这样您的密码才会以明文形式发送!)。这来自我的脚本,它对我有用:
server = smtplib.SMTP()
server.connect("smtp.gmail.com", "submission")
server.starttls()
server.ehlo()
server.login(user, password)
答案 1 :(得分:3)
以下是在Python中使用gmail发送电子邮件的方法:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user@gmail.com', getpass('Gmail password:')
# create message
msg = MIMEText('message body…', _charset='utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = login
# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
s.login(login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
s.quit()
答案 2 :(得分:2)
我发现在通过gmail发送邮件之前我必须先做一个ehlo()和一个starttls():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(SERVER_EMAIL,EMAIL_HOST_PASSWORD)
它不应该对登录产生影响,但是我使用来自email.mime.multipart的MIMEMultipart作为正文,例如:
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = mFrom
msg['To'] = mTo
if textBody:
part1 = MIMEText(textBody, 'plain')
msg.attach(part1)
if htmlBody:
part2 = MIMEText(htmlBody, 'html')
msg.attach(part2)
BODY = msg.as_string()