2011-11-30 107 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()