Having trouble with sending an email through SMTP Python(通过 SMTP Python 发送电子邮件时遇到问题)
问题描述
因此,我尝试使用 Python 通过 SMTPlib 发送电子邮件,但无法正常工作.我阅读了 Microsoft SMTP 规范,并相应地将它们放入其中,但我无法让它工作.这是我的代码:
So I'm trying to send an email through SMTPlib with Python, but I can't get it to work. I read up on the Microsoft SMTP specs, and put them in accordingly, but I can't get it to work. Here is my code:
# Send an email
SERVER = "smtp-mail.outlook.com"
PORT = 587
USER = "******@outlook.com"
PASS = "myPassWouldBeHere"
FROM = USER
TO = ["******@gmail.com"]
SUBJECT = "Test"
MESSAGE = "Test"
message = """
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, MESSAGE)
try:
server = smtplib.SMTP()
server.connect(SERVER, PORT)
server.starttls()
server.login(USER,PASS)
server.sendmail(FROM, TO, message)
server.quit()
except Exception as e:
print e
print "
Couldn't connect."
我从键盘记录器中获得了代码,但我对其进行了一些清理.我阅读了 here 了解基本 SMTP 的工作原理,但很少有像 这样的东西starttls
(方法)我不太明白.
I got the code from a keylogger, but I cleaned it up a bit. I read up here on how basic SMTP works, but there are few things like starttls
(Methods) I don't quite understand.
非常感谢您对此提供的任何帮助.
I really appreciate any help with this.
推荐答案
试试这个.这适用于 Python 2.7.
Try this. This works in Python 2.7.
def send_mail(recipient, subject, message):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
username = "sender@outlook.com"
password = "sender's password"
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(message))
try:
print('sending mail to ' + recipient + ' on ' + subject)
mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(username, password)
mailServer.sendmail(username, recipient, msg.as_string())
mailServer.close()
except error as e:
print(str(e))
send_mail('recipient@example.com', 'Sent using Python', 'May the force be with you.')
这篇关于通过 SMTP Python 发送电子邮件时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 SMTP Python 发送电子邮件时遇到问题
基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01