簡體   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