Soham Nandy
Soham Nandy

Reputation: 13

Python module smtplib doesn't send mail

I am trying to write a program that logins with a Gmail id and sends a mail to a provided id.

import smtplib

email = input('Enter your email\n')
password = input('Enter your password\n')
reciever = input("To whom you want to send?\n")
content = input("Enter content below:\n")




mail= smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login(email,password)
mail.send_message(email,reciever,content)

But when I execute the program I get this error...

Enter your email
[email protected]
Enter your password
x
To whom you want to send?
[email protected]
Enter content below:
HELLOOOO
Traceback (most recent call last):
  File "c:/Users/soham/Desktop/Python Crack/main.py", line 15, in <module>
    mail.send_message(email,reciever,content)
  File "C:\Users\soham\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 928, in send_message
    resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'
PS C:\Users\soham\Desktop\Python Crack> 

P.S- I am writing x instead of my password for security issue (In the program the password is correct)

Upvotes: 1

Views: 1249

Answers (2)

Rafa&#243;
Rafa&#243;

Reputation: 599

You need to pass MIMEMultipart object, not strings, when you use send_message:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# collect data from user
email = input('Enter your email\n')
password = input('Enter your password\n')
reciever = input("To whom you want to send?\n")
content = input("Enter content below:\n")

# set up a server
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(email, password)

# create and specify parts of the email
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = reciever
msg['Subject'] = 'sample subject' # maybe you want to collect it as well?

msg.attach(MIMEText(content, 'plain'))

mail.send_message(msg)
mail.quit()

Upvotes: 3

incarnadine
incarnadine

Reputation: 700

You are using the wrong function to send your email. You should use mail.sendmail() instead of mail.send_message(). The difference is the order of the arguements and in the first function, the message is a string, in the second it is a Message object.

https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail

Upvotes: 1

Related Questions