需要
pip install dnspython
然后使用自己名下的域名发送:
import smtplib
import dns.resolver
from email.message import EmailMessage
from email.utils import make_msgid, formatdate
rctp_tos = ['290475975@sjtu.edu.cn', 'mail@shishuyang.cn']
msg = EmailMessage()
msg.set_content('这里是邮件内容。')
msg['Subject'] = '这里是邮件标题。'
msg['From'] = 'mail@netsci2022.net'
#msg['From'] = 'kding@mail.sioc.ac.cn'
msg['To'] = ', '.join(rctp_tos)
msg['Message-ID'] = make_msgid(domain='netsci2022.net')
print(msg['Message-ID'])
msg['Date'] = formatdate(localtime=True)
#msg.add_alternative('<html><body><h1>这里可以加上HTML标签。</h1></body></html>', subtype='html')
# Send the email via the recipient's SMTP server
for recipient in rctp_tos:
domain = recipient.split('@')[1]
mx_records = dns.resolver.resolve(domain, 'MX')
mx_record = sorted(mx_records, key=lambda r: r.preference)[0]
mx_hostname = mx_record.exchange.to_text()
try:
with smtplib.SMTP(mx_hostname) as smtp:
smtp.send_message(msg)
print(f'Email forwarded to {recipient} via {mx_hostname}')
except Exception as e:
print(f'Failed to forward email to {recipient}: {e}')
在自己的DNS控制台:
- 新建一个MX类型的@记录,记录值似乎不重要。
- 新建一个TXT类型的@记录,记录值为v=spf1 ip4:118.25.81.228 ip4:118.25.81.229 ~all 表示允许发送邮件的IP地址。可以使用多个ip地址。
即使域名不是自己的,也有机会发送成功。测试下来,如果使用一个真实存在的域名,发送失败或者进垃圾邮件的概率会很高。如果是一个不真实存在的域名,则这个概率会小一点。当然谷歌邮箱还是NB,它会ban掉此类邮件,并且返回值中告诉你应该怎么做。