2012-06-29 93 views
3

我想創建一個簡單的python腳本發送電子郵件。我用這個下面的代碼:發送電子郵件與python

import subprocess 

params = {'from': '[email protected]', 
      'to':  '[email protected]', 
      'subject': 'Message subject'} 

message = '''From: %(from)s 
To: %(to)s 
Subject: %(subject)s 

Message body 

''' % params 

sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']]) 
sendmail.communicate(message) 

但我recive以下錯誤消息時,我嘗試運行它:

Traceback (most recent call last): 
    File "/home/me/test.py", line 15, in <module> 
    sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']]) 
    File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ 
    errread, errwrite) 
    File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child 
    raise child_exception 
OSError: [Errno 13] Permission denied 

任何人都知道解決這個問題,或者一個更好的代碼?

謝謝!

+0

而不是調用sendmail二進制文件,你可以使用內置的smtp庫http://docs.python.org/library/email-examples.html – Gryphius

+0

我會試試看,謝謝! – fatninja

+0

任何特殊原因**不能**使用python的smtplib或email模塊? – guidot

回答

2

/usr/share/sendmail是非常不尋常的 - 你確定你的sendmail二進制文件實際上存在嗎?通常在/usr/sbin/sendmail

我寧願使用標準庫smptlib,而不是直接調用sendmail,如果我是你的話。

您可以使用它像這樣發送消息:

server = smtplib.SMTP('smtp.example.com') 
server.sendmail(fromaddr, toaddrs, msg) 
server.quit() 
+0

我在終端寫了whereis sendmail,/ usr/share/sendmail是它的迴應。但是我現在已經將sendmail文件夾移到了/ usr/sbin中,同時給出了相同的errormsg。 – fatninja

+0

這是無關緊要的,但sendmail實際上是否從命令行工作? – azmo

2

而不是調用特定的過程中,你可以,如果你的郵件被配置爲直接使用專用的郵件庫:

import smtplib 
from email.mime.text import MIMEText 

fp = open(textfile, 'rb') 
# Create a text/plain message 
msg = MIMEText(fp.read()) 
fp.close() 

# Format headers 
msg['Subject'] = 'My subject' 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 

# Send the message via Michelin SMTP server, but don't include the envelope header. 
s = smtplib.SMTP('your mail server') 
s.sendmail('[email protected]', ['[email protected]'], msg.as_string()) 
s.quit() 

文檔中有更多python email examples

+0

謝謝,我會試試! – fatninja

+0

當我嘗試運行它時,我收到以下errormsg:錯誤:[Errno 111]連接被拒絕。 – fatninja

+0

所以這是一個SMTP服務器配置錯誤。你有沒有嘗試用'localhost'作爲服務器? – Emmanuel

1

下面是一些代碼,使用發送電子郵件的smtplib,並能做到TLS/SSL

import smtplib 
from email.MIMEText import MIMEText 
from email.utils import parseaddr 

class Mailer(object): 
    def __init__(self, fromAddress, toAddress, password): 
     self.fromAddress = parseaddr(fromAddress)[1] 
     self.toAddress = parseaddr(toAddress)[1] 
     self.password = password 

    def send(self, subject, body): 
     msg = MIMEText(body) 
     msg["From"] = self.fromAddress 
     msg["Reply-to"] = self.toAddress 
     msg["To"] = self.toAddress 
     msg["Subject"] = subject 

     sender = msg["From"] 
     recipient = msg["To"] 

     messageText = "".join(str(msg)) 
     mxhost = self.lookup(sender) # lookup finds the host that you want to send to 

     server = smtplib.SMTP(mxhost, 587) #port 465 or 587 
     server.ehlo() 
     server.starttls() 
     server.ehlo() 
     server.login(sender, self.password) 
     server.sendmail(sender, recipient, messageText) 
     server.close() 
0

這是我的代碼發送電子郵件。

#coding: utf-8 

import smtplib 
from email.mime.text import MIMEText 
from email.utils import formatdate 

def send_mail(to_list,sub,content): 
    mail_host="smtp.example.com" 
    mail_user="nvi" 
    mail_pass="password" 
    mail_postfix="example.com" 
    me=mail_user + '555' +"<"+mail_user+"@"+mail_postfix+">" 
    msg = MIMEText(content, _subtype='plain', _charset='utf-8') 
    msg['Subject'] = sub 
    msg['From'] = me 
    msg['To'] = to_list 
    msg['Date'] = formatdate(localtime=True) 
    msg['Bcc'] = '[email protected]' 
    try: 
     s = smtplib.SMTP() 
     s.connect(mail_host) 
     s.login(mail_user,mail_pass) 
     s.sendmail(me, to_list, msg.as_string()) 
     s.close() 
     return True 
    except Exception, e: 
     print e 
     return False 


if __name__ == "__main__": 
    send_mail('my_email_address', 'subject', 'content') 
0

我的程序可以和gMail一起工作,你可以嘗試和其他任何東西一起玩。您也可以發送短信。我在下面附上我的代碼。

import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders 
Type = input("Enter 1 for eMail, 2 for SMS: ") 
toaddr = 0 
if Type=='1': 
    toaddr = input("Enter to address: ") 
else: 
    Provider = input("1 for Sprint, 2 for AT&T, and 3 for Verizon: ") 
    Mobile = input("Enter the mobile number: ") 
    if Provider=='1': 
     toaddr = str(Mobile) + "@messaging.sprintpcs.com" 
    if Provider=='2': 
     toaddr = str(Mobile) + '@txt.att.net' 
    if Provider=='3': 
     toaddr = str(Mobile) + '' 
    print (toaddr)  
head = input("Enter your subject: ") 
body = input("Enter your message: ") 
fromaddr = input("Enter the 'From Address'([email protected]): ") 
msg = MIMEMultipart() 
msg['From'] = fromaddr 
msg['To'] = toaddr 
msg['Subject'] = head 
password = input("Enter the from address password: ") 
msg.attach(MIMEText(body, 'plain')) 
server = smtplib.SMTP('smtp.gmail.com', 587) 
server.starttls() 
server.login(fromaddr, password) 
text = msg.as_string() 
server.sendmail(fromaddr, toaddr, text) 
server.quit() 

我希望這會有所幫助。