Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 :

<?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 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.

"""

try:

   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

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...