如何在没有身份验证的情况下直接向 SMTP 服务器发送邮件?

2022-01-17 00:00:00 python authentication smtp gmail

问题描述

我想通过直接连接到 smtp.gmail.com 直接从脚本向 Gmail 电子邮件帐户发送电子邮件.

I would like to send an email directly from a script to a Gmail email account, by connecting directly to smtp.gmail.com.

但是,我不希望脚本中包含 gmail 密码.根据我的阅读,Gmail 似乎需要验证才能发送任何邮件,包括发送给自己的用户.

However, I would prefer not to have the gmail password in the script. From what I have read, it appears that Gmail requires authentication before it will deliver any mail, including to its own users.

我的问题是,来自另一台 SMTP 服务器的邮件是如何传递的,因为该 SMTP 服务器没有 Gmail 凭据.Gmail 是否只需要对匿名"发件人进行身份验证,并且由于我的脚本在个人计算机上运行,​​因此需要更高的安全性?这是我正在运行的 python 脚本:

My question is, how is mail coming from another SMTP server ever delivered, since that SMTP server will not have Gmail credentials. Does Gmail only require authentication for "anonymous" senders, and since my script is running on a personal computer, it is subject to higher security? Here is the python script I am running:

import smtplib
import email
msg = email.message.Message()
msg["From"] = "user@gmail.com"
msg["To"] = "user@gmail.com"
msg["Subject"] = "Test message"
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
server.ehlo_or_helo_if_needed()
try:
    failed = server.sendmail("user@gmail.com","user@gmail.com", msg.as_string())
    server.close()
except Exception as e:
    print(e)

当我运行这个脚本时,输出是:

When I run this script, the output is:

(530, b'5.5.1 Authentication Required. Learn more at
5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 fw5sm21125889wib.0', 'user@gmail.com')

我的问题是,外部 SMTP 服务器如何避免这个问题?他们所做的一切是否可以在本地脚本中复制,还是需要正确的反向 DNS 记录、SPF 记录等?

My question is, how do external SMTP servers avoid this problem? And is whatever they do replicable in a local script, or does it require correct reverse DNS records, SPF records, etc.?


解决方案

你可以使用一些无需认证的外部 SMTP 服务器(或本地 SMTP),但是发送的邮件会被 Google 的垃圾邮件过滤器捕获,因为 msg["From"] 是 @google.com,而实际的 SMTP 不是 smtp.gmail.com.

You can use some external SMTP servers without authentication (or a local SMTP), but the sent message will be caught by Google's spam filter because the msg["From"] is @google.com, while the actual SMTP is not smtp.gmail.com.

那些 SMTP 服务器也必须在 ISP 的 DNS 中有正确的反向区域,否则这个 smtp 将被 google 阻止.

Those SMTP servers also must have correct reverse zone in ISP's DNS and otherwise this smtp will be blocked by google.

相关文章