简体   繁体   English

如何从python发送电子邮件

[英]How to send email from python

My Code 我的守则

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] No connection could be made because the target machine actively refused it ConnectionRefusedError:[WinError 10061]无法建立连接,因为目标计算机主动拒绝它

Note: 注意:

  • Not having a SMTP server 没有SMTP服务器

This code will help you to send the email. 此代码将帮助您发送电子邮件。 You just need to provide your email-id password. 您只需提供您的电子邮件ID密码即可。

The most important note is: don't give file name as email.py. 最重要的注意事项是:不要将文件名称为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"

I would suggest using a package like yagmail , rather than trying to figure out how to get smtplib to work. 我建议使用像yagmail这样的软件包 ,而不是试图弄清楚如何让smtplib工作。 Disclaimer: I'm the maintainer of yagmail. 免责声明:我是yagmail的维护者。

Code would look like: 代码看起来像:

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