5

我正在尝试在 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.
4

3 回答 3

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)
于 2012-08-19T21:35:46.383 回答
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()
于 2012-08-19T22:07:52.130 回答
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()
于 2012-08-19T21:51:03.287 回答