Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

Good evening, guys. I'm a PHP programmer. I know with PHP, we can send a mail with the help of a server directly, like the following code :


$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 the case of Python, we have to use smtplib and Gmail or any other Hotmail servers for sending an email. I just want to find is there any way to send an email directly from the server with the help of Python?

1 Answer

0 votes
by (26.4k points)

To send an email via local SMTP

If you have a SendMail(Which is a local SMTP server), check whether it is listening as expected

netstat -tuna

You should've noticed that it's listening on the loopback address on port 25

See, If it's listening, you can be able to do this in 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.



   smtpObj = smtplib.SMTP('localhost')

   smtpObj.sendmail(sender, receivers, message)         

   print("Successfully sent email")

except SMTPException:

   print("Error: unable to send email")

Want to learn more about Python? Come, and join the Python Course course

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Mar 2, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 22, 2020 in Azure by dante07 (13.1k points)

Browse Categories