2016-09-14 185 views
1

我的代碼如何從蟒蛇

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 = "[email protected]" 
me = "[email protected]" 
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

注發送電子郵件:

  • 沒有一個SMTP服務器
+2

你有一個SMTP服務器上的本地主機上運行? –

+0

我不這麼認爲,我正在使用Windows 7 – RajivKumar

+3

然後你需要一個SMTP服務器(你自己或任何其他你有一個帳戶)。 –

回答

0

此代碼將幫助您發送電子郵件。 你只需要提供你的電子郵件密碼。

最重要的注意事項是:不要將文件名稱作爲email.py。

import socket 
import sys 
import smtplib 
EMAIL_TO = ["[email protected]"] 
EMAIL_FROM = "[email protected]" 
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("[email protected]", 'password') # you account email password.. 
    mail.sendmail("[email protected]", EMAIL_TO, msg.as_string()) 
    mail.quit() 
except Exception,e: 
    print e 
finally: 
    print "Error of email sending mail" 
+0

如何使用本地主機發送電子郵件? – RajivKumar

+0

可能是你需要一個電子郵件服務器,因爲你不能從本地主機發送它。 –

0

我建議使用像yagmail這樣的包,而不是試圖弄清楚如何讓smtplib工作。免責聲明:我是yagmail的維護者。

代碼是這樣:

import yagmail 
yag = yagmail.SMTP(host="127.0.0.1") 
yag.send(to"[email protected]", subject="subject", contents="content") 
+0

with open(os.path.expanduser(「〜/ .yagmail」))as f: FileNotFoundError:[Errno 2]沒有這樣的文件或目錄:'C:\\ Users \\ rajivkum/.yagmail' >> >我遇到了yagmail的這個錯誤 – RajivKumar

+0

正如你注意的那樣,沒有密碼和用戶名:-)運行一次'yagmail.register(「username」,「password」)''它會將你的密碼保存在你的操作系統密鑰環中。在用戶文件夾中的.yagmail文件中使用您的用戶名將允許無密碼腳本。或者:'yagmail.SMTP(「username」,「password」)'如果你喜歡在腳本中寫入用戶名/密碼。 – PascalVKooten

+0

在你的情況下,你會把'.yagmail'放到你的'C:\ Users \ rajivkum'文件夾中。 – PascalVKooten