2011-11-30 78 views
-2

我想發送帶有自定義「FROM」字段的電子郵件,例如* [email protected]_company.com*,在PHP中使用它很容易,但我不知道如何在Python中執行此操作,並且可以找不到任何好的文檔。使用Python的非SMTP電子郵件

換句話說,什麼是下面的PHP代碼的python等價物?

$to = "[email protected]"; 
$subject = "Weekly news"; 
$message = "Hello, you've got new Like"; 
$from = "[email protected]_company.com"; 
$headers = "From: WeekNews" . '<'.$from.'>'; 
mail($to,$subject,$message,$headers); 

請注意,沒有必要設置SMTP服務器連接,您只需給它一個自定義$從地址。

+0

我不知道。那麼如何從我的本地主機發送一個,而不是使用Gmail等電子郵件服務? – NoobDev4iPhone

+2

SMTP是發送電子郵件的地方,它只是有些時候它並未反映在代碼中,因爲默認情況是假設的或配置文件被引用。 –

回答

2

你將永遠不得不將它發送到某個smtp服務器,這實際上也是php的功能,它使用windows上的php.ini和unix上的本地郵件傳送系統中的設置。 http://php.net/manual/en/function.mail.php

從Python文檔: http://docs.python.org/py3k/library/email-examples.html

mailFrom = '[email protected]' 
mailTo = ['[email protected]', '[email protected]'] 
subject = 'mail subject' 
message = 'the message body' 

# Create message container - the correct MIME type is multipart/alternative. 
msg = MIMEMultipart('alternative') 
msg['Subject'] = subject 
msg['From'] = mailFrom 
msg['To'] = ", ".join(mailTo) 
# Record the MIME types of both parts - text/plain and text/html. 
part1 = MIMEText(message, 'text') 
part2 = MIMEText(message, 'html') 

# Attach parts into message container. 
# According to RFC 2046, the last part of a multipart message, in this case 
# the HTML message, is best and preferred. 
msg.attach(part1) 
msg.attach(part2) 

# Send the message via local SMTP server. 
s = smtplib.SMTP('localhost') 
# sendmail function takes 3 arguments: sender's address, recipient's address 
# and message to send - here it is sent as one string. 
failed_addr = s.sendmail(mailFrom, mailTo, msg.as_string()) 
print("failed addresses: {f}".format(f = failed_addr)) 
s.quit()