python - 使用 SMTP 从 Python 发送邮件

标签 python smtp

我正在使用以下方法通过 SMTP 从 Python 发送邮件。这是正确的使用方法还是我遗漏了一些问题?

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')

from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"

subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" 
        % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

最佳答案

我使用的脚本非常相似;我在这里发布它作为如何使用 email.* 模块生成 MIME 消息的示例;所以这个脚本可以很容易地修改为附加图片等。

我依靠我的 ISP 添加日期时间 header 。

我的 ISP 要求我使用安全的 smtp 连接来发送邮件,我依赖 smtplib 模块(可在 http://www1.cs.columbia.edu/~db2501/ssmtplib.py 下载)

在您的脚本中,用于在 SMTP 服务器上进行身份验证的用户名和密码(下面给出虚拟值)在源代码中以纯文本形式显示。这是一个安全漏洞;但最好的选择取决于您需要(想要?)保护这些。

========================================

#! /usr/local/bin/python


SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'


content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except:
    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

关于python - 使用 SMTP 从 Python 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64505/

相关文章:

PHP 代码点火器 : Is there an elegant way to to get the SMTP return code upon a mail failure

python - 将 Flask 应用程序部署到 heroku 会导致 create_app() 出现 500 错误

JavaMail SSL 无论如何都没有身份验证信任证书

python - 检查字符串为 1, 0 否则打印字符串

python - 生成具有多个(多组多组多组)X轴数据集的图

java - 如何重用与 JavaMail 的连接以避免 AuthenticationFailedException : Too many login attempts?

ruby-on-rails - ¨504 5.7.4 无法识别的身份验证类型¨ Rails 应用程序到 MS Exchange

Oracle 数据库 : possible to send email from PL/SQL through proxy server?

python - 如何使用python opencv计算两个人之间的距离?

python - 在 Django 中重写此数据库访问查询以规避 'DISTINCT ON' 错误