I am successfully able to send email using the smtplib module. But when the emial is sent, it does not include the subject in the email sent.
import smtplib SERVER = <localhost> FROM = <from-address> TO = [<to-addres>] SUBJECT = "Hello!" message = "Test" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit()
How should I write "server.sendmail" to include the SUBJECT as well in the email sent.
If I use, server.sendmail(FROM, TO, message, SUBJECT), it gives error about "smtplib.SMTPSenderRefused"
The smtplib module The smtplib is a Python library for sending emails using the Simple Mail Transfer Protocol (SMTP). The smtplib is a built-in module; we do not need to install it. It abstracts away all the complexities of SMTP.
Attach it as a header:
message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
and then:
server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit()
Also consider using standard Python module email
- it will help you a lot while composing emails.
This will work with Gmail and Python 3.6+ using the new "EmailMessage" object:
import smtplib from email.message import EmailMessage msg = EmailMessage() msg.set_content('This is my message') msg['Subject'] = 'Subject' msg['From'] = "[email protected]" msg['To'] = "[email protected]" # Send the message via our own SMTP server. server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("[email protected]", "password") server.send_message(msg) server.quit()
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