SMTP authentication in Python mailing script

373 Views Asked by At

Python (3.x) learner, and overall noob, here.

I am writing a very basic script to allow users to send emails from the cli.

After reading up a little (here) I followed this example as a starting point.

I became curious about SMTP, and found out that "The original SMTP specification did not include a facility for authentication of senders." (Wikipedia)

Being a newbie, I was surprised to find that I could email people, using any 'from address', without any form of authentication, by specifying certain SMTP servers, that do not, in fact, require authentication. Here is a very basic version of the program:

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

user_server = input("Input SMTP> ") 
server = smtplib.SMTP(user_server)
server.ehlo()
#server.starttls() <-- commented out 
server.ehlo()
#server.login("[email protected]","password") <-- commented out

fromaddr = input("Insert from-address> ")
toaddr = input("Insert to-address> ")
subject = input("Insert Subject> ")

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject

body = "Testing"
msg.attach(MIMEText(body, 'plain'))

text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

I'd like my script to work whether the SMTP server of choice requires authentication or not (ie: ask user to authenticate when needed).

How could I do that? what functions/modules/parameters would be required?

0

There are 0 best solutions below