how to send email with python directly from server and without smtp

冷暖自知 提交于 2019-12-21 06:49:10

问题


I'm php programmer and with php you can send email with server directly, for example this code send email to client:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?> 

but in python you have to use smtplib and gmail or hotmail servers for sending email. I wonder is there anyway to send email with python direct from server?


回答1:


Other Options

When you use the mail functionality in PHP it is using the local sendmail of the host you are on, which in turn is simply a SMTP relay locally, of course locally sending emails is not really suggested as these are likely not have a good delivery rate due to DKIM, SPF and other protection mechanisms. If you care about deliverability I would recommend using either

a) An external SMTP server to send mail via which is correctly configured for the sending domain.

b) An API such as AWS SES, Mailgun, or equivalent.

If you do not care about deliverability then you can of course use local SendMail from Python, SendMail listens on the loopback address (127.0.0.1) on port 25 just like any other SMTP server, so you may use smtplib to send via SendMail without needing to use an external SMTP server.

Sending Email via Local SMTP

If you have a local SMTP server such as SendMail check it is listening as expected...

netstat -tuna

You should see it listening on the loopback address on port 25.

If it's listening then you should be able to do something like this from Python to send an email.

import smtplib

sender = 'no_reply@mydomain.com'
receivers = ['person@otherdomain.com']

message = """From: No Reply <no_reply@mydomain.com>
To: Person <person@otherdomain.com>
Subject: Test Email

This is a test e-mail message.
"""

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


来源:https://stackoverflow.com/questions/54184900/how-to-send-email-with-python-directly-from-server-and-without-smtp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!