2011-08-29 44 views
33

我成功地能夠使用smtplib模塊發送電子郵件。但是,當emial發送時,它不包括髮送電子郵件中的主題。Python:使用smtplib模塊發送電子郵件時未顯示「主題」

import smtplib 

SERVER = <localhost> 

FROM = <from-address> 
TO = [<to-addres>] 

SUBJECT = "Hello!" 

message = "Test" 

TEXT = "This message was sent with Python's smtplib." 
server = smtplib.SMTP(SERVER) 
server.sendmail(FROM, TO, message) 
server.quit() 

我應該如何編寫「server.sendmail」以在發送的電子郵件中包含SUBJECT。

如果我使用,server.sendmail(發件人,收件人,郵件,分科),它提供了錯誤關於 「smtplib.SMTPSenderRefused」

回答

71

附上它作爲一個標題:

message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT) 

然後:

server = smtplib.SMTP(SERVER) 
server.sendmail(FROM, TO, message) 
server.quit() 

還要考慮使用標準Python模塊email - 這將有助於ÿ在撰寫電子郵件時你會做很多事情。

+0

的作品就像一個魅力,MERCI –

2

見注在的smtplib文檔的底部:

In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.

下面是email文檔的示例部分的鏈接,它確實顯示了創建帶有主題行的消息。 http://docs.python.org/library/email-examples.html#email-examples

看來的smtplib並不直接支持主題此外,預計味精已與一個主題,等等。這是在email模塊採用格式化

2

你或許應該修改代碼以這樣的事:

from smtplib import SMTP as smtp 
from email.mime.text import MIMEText as text 

s = smtp(server) 

s.login(<mail-user>, <mail-pass>) 

m = text(message) 

m['Subject'] = 'Hello!' 
m['From'] = <from-address> 
m['To'] = <to-address> 

s.sendmail(<from-address>, <to-address>, m.as_string()) 

顯然,<>變量必須是實際的字符串值,或者有效的變量,我只是填補他們的佔位符。這適用於發送帶有主題的郵件。

+0

我收到以下錯誤:from email.mime.text將MIMEText導入爲文本 ImportError:沒有名爲mime.text的模塊 – nsh

+0

@nsh - 使用什麼版本的Python?我在這個特定的安裝上使用2.6.6。 3.x完全有可能在一個稍微不同的地方。 –

+0

我正在使用2.4.3 – nsh

2

我認爲你必須包括它的消息中:

import smtplib 

message = """From: From Person <[email protected]> 
To: To Person <[email protected]> 
MIME-Version: 1.0 
Content-type: text/html 
Subject: SMTP HTML e-mail test 

This is an e-mail message to be sent in HTML format 

<b>This is HTML message.</b> 
<h1>This is headline.</h1> 
""" 

try: 
    smtpObj = smtplib.SMTP('localhost') 
    smtpObj.sendmail(sender, receivers, message)   
    print "Successfully sent email" 
except SMTPException: 
    print "Error: unable to send email" 

代碼:http://www.tutorialspoint.com/python/python_sending_email.htm

+0

一個觀察:例如,from,to和subject字段必須位於變量「message」的VERY BEGINNING中,否則字段將不會被解釋爲它必須是預期。我有插入「主題」字段的經驗,而不是在變量的開頭,並且郵件沒有主題地來到接收者的郵箱。乾杯。 – ivanleoncz

4

試試這個:

import smtplib 
from email.mime.multipart import MIMEMultipart 
msg = MIMEMultipart() 
msg['From'] = 'sender_address' 
msg['To'] = 'reciver_address' 
msg['Subject'] = 'your_subject' 
server = smtplib.SMTP('localhost') 
server.sendmail('from_addr','to_addr',msg.as_string()) 
+2

信息的主體呢?那去哪了? – Dss

+2

我結束了這個以放在正文中https://docs.python.org/2/library/email-examples.html#id5 – Nico

相關問題