我想用我的python脚本发送电子邮件,但遗憾的是它并不像php那样简单明了,我只能使用mail()函数。
我用过这个例子:
import smtplib
FROM = "sender@example.com"
TO = ["me@gmail.com"]
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
但它只返回一大堆错误我甚至不知道...的含义
Traceback (most recent call last):
File "mylo.py", line 70, in <module>
sys.exit(main())
File "mylo.py", line 66, in main
send_mail()
File "mylo.py", line 37, in send_mail
server = smtplib.SMTP(SERVER)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 512, in create_connection
raise error, msg
socket.error: [Errno 61] Connection refused
如何使用python发送电子邮件?
答案 0 :(得分:16)
我重写了电子邮件逻辑:
#!/usr/bin/python -tt
from email.mime.text import MIMEText
from datetime import date
import smtplib
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SMTP_USERNAME = "email@gmail.com"
SMTP_PASSWORD = "yourpassword"
EMAIL_TO = ["recepient1@gmail.com", "recepient2@gmail.com"]
EMAIL_FROM = "email@gmail.com"
EMAIL_SUBJECT = "Demo Email : "
DATE_FORMAT = "%d/%m/%Y"
EMAIL_SPACE = ", "
DATA='This is the content of the email.'
def send_email():
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + " %s" % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__=='__main__':
send_email()
这是非常易配置的脚本。
答案 1 :(得分:1)
我建议您使用mailtools 2
http://pypi.python.org/pypi/mailtools/2
它可以发送纯文本和HTML电子邮件。非常容易使用。
答案 2 :(得分:-2)
我建议你使用SendGrid API。使用SendGrid API,您只需要一个简单的帐户,此代码就会发送一封电子邮件:
import sendgrid
sg = sendgrid.SendGridClient('Username','Password')
message = sendgrid.Mail()
message.add_to("Email Address of Reciever")
message.set_from("Email Address of Sender")
message.set_subject("Email Subject")
message.set_html("Email html")
sg.send(message)
有关完整文档,请查看https://sendgrid.com/docs/Integrate/Code_Examples/python.html