通过SMTP Python发送电子邮件时遇到问题 [英] 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 "\nCouldn't connect."
我从键盘记录器中获取了代码,但是我对其进行了一些清理。我在此处上了解了基本SMTP的工作原理,但是却有<$ c这样的东西$ c> 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.
对此我非常感谢。
推荐答案
尝试一下。这在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发送电子邮件时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文