这是我的脚本:

#!/usr/bin/python

import smtplib
msg = 'Hello world.'

server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('myname@gmail.com','mypass')
server.sendmail('myname@gmail.com','somename@somewhere.com',msg)
server.close()

我只是想从我的 Gmail 帐户发送一封电子邮件。由于 gmail 的要求,该脚本使用 starttls。我已经在两个网络主机 1and1 和 webfaction 上尝试过此操作。1and1 给我一个“连接被拒绝”错误,而 webfaction 没有报告错误,但只是不发送电子邮件。我看不出该脚本有任何问题,所以我认为它可能与网络主机有关。任何想法和评论将不胜感激。

编辑:我打开了调试模式。从输出来看,它似乎成功发送了消息......我只是从未收到它。

send: 'ehlo web65.webfaction.com\r\n'
reply: '250-mx.google.com at your service, [174.133.21.84]\r\n'
reply: '250-SIZE 35651584\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-STARTTLS\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 PIPELINING\r\n'
reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84]
SIZE 35651584
8BITMIME
STARTTLS
ENHANCEDSTATUSCODES
PIPELINING
send: 'STARTTLS\r\n'
reply: '220 2.0.0 Ready to start TLS\r\n'
reply: retcode (220); Msg: 2.0.0 Ready to start TLS
send: 'ehlo web65.webfaction.com\r\n'
reply: '250-mx.google.com at your service, [174.133.21.84]\r\n'
reply: '250-SIZE 35651584\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-AUTH LOGIN PLAIN\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250 PIPELINING\r\n'
reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84]
SIZE 35651584
8BITMIME
AUTH LOGIN PLAIN
ENHANCEDSTATUSCODES
PIPELINING
send: 'AUTH PLAIN *****\r\n'
reply: '235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: 2.7.0 Accepted
send: 'mail FROM:<myname@gmail.com> size=12\r\n'
reply: '250 2.1.0 OK 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48
send: 'rcpt TO:<myname@gmail.com>\r\n'
reply: '250 2.1.5 OK 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48
send: 'data\r\n'
reply: '354  Go ahead 4sm652580yxq.48\r\n'
reply: retcode (354); Msg: Go ahead 4sm652580yxq.48
data: (354, 'Go ahead 4sm652580yxq.48')
send: 'Hello world.\r\n.\r\n'
reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n'
reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48
data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48')
有帮助吗?

解决方案

我认为Gmail SMTP服务器对您连接的IP地址进行反向DNS查找,并在找不到域(如果找不到域)时拒绝连接。这是为了避免使用垃圾邮件发送者将其SMTP服务器用作开放继电器。

其他提示

您是否尝试过构建有效的消息?

from email.MIMEText import MIMEText

msg = MIMEText('body')
msg['Subject'] = 'subject'
msg['From'] = "..."
msg['Reply-to'] = "..."
msg['To'] = "..."

我不知道OP是否仍然在乎这个答案,但是在这里发现自己是为了解决类似问题的问题,希望其他人可能会发现这有用。事实证明,Google改变了允许使用SMTP服务器的方式。您将要检查几件事:

  1. 您使用的是与“来自”地址相同的地址。如果我没记错的话,那曾经是这样的情况,您几乎可以将您想要的任何内容放在野外,但是出于安全目的,许多SMTP主机网站(包括Google)现在将其限制在已对其进行认证的地址。

  2. 允许“不太安全的应用程序”访问您的帐户(读取:我们不会从中产生收入的应用程序)。要登录您的帐户并在此处导航:https://www.google.com/settings/security/lesssecureapps

  3. 使用带有TLS的端口587。不太确定为什么,但是我永远无法让港口465玩得很好。

希望这对别人有帮助。

这里有些自我推销,但我觉得有道理。

实际上,您只需要这段代码即可完全执行您所编写的操作:

import yagmail
yag = yagmail.SMTP('myname@gmail.com')
yag.send('somename@somewhere.com', subject = None, contents = 'Hello')

或者单衬:

yagmail.SMTP('myname@gmail.com').send('somename@somewhere.com', None, 'Hello world.')

好处是我建议使用密钥环来存储您的密码,这样您就不会面临别人在脚本中看到您的密码的风险。

您可以通过在解释器中运行一次来​​进行设置:

import yagmail
yagmail.register("my@gmail.com", "mypassword")

并退出。然后你就可以使用:

import yagmail
yagmail.SMTP("my@gmail.com") # without password

如果您在主目录中添加带有“my@gmail.com”的 .yagmail,那么您可以执行以下操作: yagmail.SMTP(), ,但现在这毫无意义。

警告:如果您真的想发送大量消息,最好设置 OAuth2,yagmail 可以帮助您实现这一点。

yagmail.SMTP("my@gmail.com", oauth2_file="/path/to/save/creds.json")

第一次运行时,它将引导您完成获取 OAuth2 凭据并将其存储在文件中的过程,以便下次您不需要对其执行任何操作。您是否怀疑有人发现了您的凭据?他们的权限有限,但您最好通过 Gmail 使他们的凭据失效。

对于软件包/安装请查看 git 或者 阅读文档, ,适用于 Python 2 和 3。

您需要在Gmail中检查您的“已发送”文件夹,因为这是从您的帐户发送到帐户的消息很可能会出现。

我转到了上述链接,与要发送的地址有3个不同的链接,但我收到了三封到同一地址的电子邮件,并且是#3地址。

http://mynthon.net/howto/-/python/python%20-%20logging.smtphandler-how-to-so-use-cus-gmail-gmail-smtp-server.txt

import logging
import logging.handlers

class TlsSMTPHandler(logging.handlers.SMTPHandler):
def emit(self, record):
    """
    Emit a record.

    Format the record and send it to the specified addressees.
    """
    try:
        import smtplib
        import string # for tls add this line
        try:
            from email.utils import formatdate
        except ImportError:
            formatdate = self.date_time
        port = self.mailport
        if not port:
            port = smtplib.SMTP_PORT
        smtp = smtplib.SMTP(self.mailhost, port)
        msg = self.format(record)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                        self.fromaddr,
                        string.join(self.toaddrs, ","),
                        self.getSubject(record),
                        formatdate(), msg)
        if self.username:
            smtp.ehlo() # for tls add this line
            smtp.starttls() # for tls add this line
            smtp.ehlo() # for tls add this line
            smtp.login(self.username, self.password)
        smtp.sendmail(self.fromaddr, self.toaddrs, msg)
        smtp.quit()
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        self.handleError(record)

logger = logging.getLogger()

gm = TlsSMTPHandler(("smtp.gmail.com", 587), 'myusername@gmail.com', ['address1@gmail.com', 'address2@gmail.com', 'address3@gmail.com'], 'unable to find Error!', ('myusername@gmail.com', 'mypassword'))
gm.setLevel(logging.ERROR)

logger.addHandler(gm)

try:
    1/0
except:
    logger.exception('It NO work for me!!-')

其作品

'''
Created on 2017/11/27

@author: devuser
'''

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

FROM_ADDRESS = 'sender@gmail.com'
MY_PASSWORD = 'password'
TO_ADDRESS = 'receiver@test.co.jp'
BCC = 'receiver2@test.net'
SUBJECT = 'GmailのSMTPサーバ経由'
BODY = 'pythonでメール送信'


def create_message(from_addr, to_addr, bcc_addrs, subject, body):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Bcc'] = bcc_addrs
    msg['Date'] = formatdate()
    return msg


def send(from_addr, to_addrs, msg):
    smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
    smtpobj.ehlo()
    smtpobj.starttls()
    smtpobj.ehlo()
    smtpobj.login(FROM_ADDRESS, MY_PASSWORD)
    smtpobj.sendmail(from_addr, to_addrs, msg.as_string())
    smtpobj.close()


if __name__ == '__main__':

    to_addr = TO_ADDRESS
    subject = SUBJECT
    body = BODY

    msg = create_message(FROM_ADDRESS, to_addr, BCC, subject, body)
    send(FROM_ADDRESS, to_addr, msg)

https://qiita.com/okhrn/items/630A87CE1A44778BBEB1

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top