繁体   English   中英

如何从python发送电子邮件

[英]How to send email from python

我的守则

import smtplib
import socket
import sys
from email.mime.text import MIMEText
fp = open("CR_new.txt", 'r')
msg = MIMEText(fp.read())
fp.close()

you = "rajiv@domain.com"
me = "rajiv@domain.com"
msg['Subject'] = 'The contents of %s' % "CR_new.txt"
msg['From'] = you
msg['To'] = me
s = smtplib.SMTP('127.0.0.1')
s.sendmail(you,me, msg.as_string())
s.quit()

ConnectionRefusedError:[WinError 10061]无法建立连接,因为目标计算机主动拒绝它

注意:

  • 没有SMTP服务器

此代码将帮助您发送电子邮件。 您只需提供您的电子邮件ID密码即可。

最重要的注意事项是:不要将文件名称为email.py。

import socket
import sys
import smtplib
EMAIL_TO = ["rajiv@domain.com"]
EMAIL_FROM = "rajiv@domain.com"
EMAIL_SUBJECT = "Test Mail... "
msg= {}
EMAIL_SPACE = ", "



msg['Subject'] = EMAIL_SUBJECT 
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
try:
    mail = smtplib.SMTP_SSL('smtp.bizmail.yahoo.com',465)
    # 
    # if you are using gmail then  use
    #   smtplib.SMTP_SSL('smtp.gmail.com',587)
    #
    mail.login("rajiv@domain.com", 'password')   # you account email password..
    mail.sendmail("rajiv@domain.com", EMAIL_TO, msg.as_string())   
    mail.quit()
except Exception,e:
    print e
finally:
    print "Error of email sending mail"

我建议使用像yagmail这样的软件包 ,而不是试图弄清楚如何让smtplib工作。 免责声明:我是yagmail的维护者。

代码看起来像:

import yagmail
yag = yagmail.SMTP(host="127.0.0.1")
yag.send(to"rajiv@domain.com", subject="subject", contents="content")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM