I'm php programmer and with php you can send email with server directly, for example this code send email to client:
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\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?
The simplest way to send a message is to use QuickSend method of Smtp class (this method is static, it does not require you to create an instance of Smtp class). QuickSend method allows you to send e-mails out even if you do not have an SMTP relay server.
Below you can find an example of a simple Python script that shows how one can send an email from a local SMTP. import smtplib sender = '[email protected]' receivers = ['[email protected]'] message = """From: From Person <[email protected]> To: To Person <[email protected]> Subject: SMTP email example This is a test message.
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
An external SMTP server to send mail via which is correctly configured for the sending domain.
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 = '[email protected]'
receivers = ['[email protected]']
message = """From: No Reply <[email protected]>
To: Person <[email protected]>
Subject: Test Email
This is a test e-mail message.
"""
try:
smtp_obj = smtplib.SMTP('localhost')
smtp_obj.sendmail(sender, receivers, message)
print("Successfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With