用Python在Mac或Linux上发送电子邮件的最佳方式?

2024-04-25 09:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用我的python脚本发送电子邮件,但不幸的是,它不像php那样简单和流畅,在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发送电子邮件?


Tags: inpyselfserverliblinelibrarymail
3条回答

我建议你用mailtools 2http://pypi.python.org/pypi/mailtools/2

它可以发送纯文本和HTML电子邮件。很容易使用。

我建议您使用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

我重写了电子邮件逻辑:

#!/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()

这是非常可配置的脚本。

相关问题 更多 >

    热门问题