使用Python的非SMTP电子邮件

使用Python的非SMTP电子邮件,python,Python,我想发送带有自定义“发件人”字段的电子邮件,如*noreply@example_company.com*,在PHP中很容易做到,但我不知道如何在python中做到这一点,也找不到任何好的文档 换句话说,以下php代码的python等价物是什么 $to = "user@gmail.com"; $subject = "Weekly news"; $message = "Hello, you've got new Like"; $from = "noreply@example_company.com"

我想发送带有自定义“发件人”字段的电子邮件,如*noreply@example_company.com*,在PHP中很容易做到,但我不知道如何在python中做到这一点,也找不到任何好的文档

换句话说,以下php代码的python等价物是什么

$to = "user@gmail.com";
$subject = "Weekly news";
$message = "Hello, you've got new Like";
$from = "noreply@example_company.com";
$headers = "From: WeekNews" . '<'.$from.'>';
mail($to,$subject,$message,$headers);
$to=”user@gmail.com";
$subject=“每周新闻”;
$message=“你好,你有了新的爱好”;
$from=”noreply@example_company.com";
$headers=“From:weeknows”。”;
邮件($to、$subject、$message、$headers);

请注意,不需要设置SMTP服务器连接,只需给它一个自定义的$from地址。

您将始终需要将其发送到某个SMTP服务器,实际上php也会这样做,它使用windows上php.ini的设置和unix上本地邮件传递系统的设置。

从python文档中:


我不知道。那么,我如何从本地主机发送电子邮件,而不是使用gmail之类的电子邮件服务呢?SMTP是发送电子邮件的工具,只是有时候它不会反映在代码中,因为默认设置是假定的,或者引用了配置文件。
mailFrom = 'from.user@somedomain.com'
mailTo = ['to.user1@somedomain.com', 'to.user2@somedomain.com']
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()