O365 smtp as relay implementation - python-3.x

I am using the below lines of code to send an email but I get the error as 'smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful' . This must be due to MFA. what can I do to authenticate?
import smtplib, ssl
port = 587 # For starttls
smtp_server = "smtp.office365.com"
sender_email = "myemail#companycom"
receiver_email = "myemail#companycom"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)

The solution to this issue is to manage the app password in your account or request for service accounts to your admin which doesn't have MFA.

Related

Unable to Send an email via python- Error- smtplib.SMTPServerDisconnected: Connection unexpectedly closed

port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Enter receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as smtp:
smtp.login(sender_email, password)
smtp.sendmail(sender_email, receiver_email, Subject, message)
I tried checking if there is any auth failure.Email could not be sent. I got following error msg.
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly
closed`
import smtplib ##Import needed modules
import ssl
port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
try:
print("Connecting to server...")
yahoo_server = smtplib.SMTP(smtp_server, port)
yahoo_server.starttls(context=context)
yahoo_server.login(sender_email, password)
print("Connected to server!")
print(f"Sending email to - {receiver_email}")
yahoo_server.sendmail(sender_email, receiver_email, Subject, message)
print("Email successfully sent to - {receiver_email}")
except Exception as e:
print(e)
finally:
yahoo_server.quit
I added a couple of modules that I didn't see. But you need those in order to use the ssl methods as well as the smtplib.
I also added a couple of print statements to help with seeing where in the process this might be getting hung up. You also want to close the connection as best practice.
lastly I added a variable to use with the steps of logging into the smtp server. I did this for Gmail recently so I don't know if this will work offhand, but at the very least the print statements and additional variables should hopefully help with that as well.

authentication error trying to send Outlook email from Python

I'm testing out a simple script to send an Outlook email from Python 3 (using Spyder).
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = 'my_username#my_company.com'
password = 'my_password'
mail_from = username
mail_to = username
mail_subject = "Test Subject"
mail_body = "This is a test message"
mimemsg = MIMEMultipart()
mimemsg['From']=mail_from
mimemsg['To']=mail_to
mimemsg['Subject']=mail_subject
mimemsg.attach(MIMEText(mail_body, 'plain'))
try:
connection = smtplib.SMTP(host='smtp.office365.com', port=587)
connection.starttls()
connection.login(username,password)
except Exception as e:
print('Got error here')
print(e)
And the output is:
Got error here
(535, b'Authentication unsuccessful, the user credentials were incorrect. [SOME_VALUE_HERE.hostname.prod.outlook.com]')
I know for sure my own username and email are correct - I verified by checking my username's properties > SMTP value. And anyway it's the username I use to login to Windows.
I'm also using the same password for logging into Windows.
Is it possible my company uses different values for host or port? Or on the backend it sends a different user name to the SMTP server?
The error indicates that SMTP authentication is disabled. Read more about that on the page at https://aka.ms/smtp_auth_disabled. The link explains how to enable SMTP AUTH for the whole organization or only for some mailboxes.
Also take a look at the following settings that would block Legacy Authentication:

send the emails using my gmail account in python?

I m trying to send emails to my users through my Gmail account but it does not work although my Gmail login credentials are also correct but it gives an error
Here is the code for Email Sending!
if request.method == 'POST':
EmailAddress = request.form['Emails']
Subject = request.form['Subject']
Message = request.form['Message']
EmailList = EmailAddress.split(',')
Message = 'Subject: {}\n\n{}'.format(Subject, Message)
for EmailName in EmailList:
Server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
Server.ehlo()
Server.login(UserEmail, UserPassword)
Server.sendmail(UserEmail, EmailName.strip(), Message)
response = "Success"
Server.quit()
Error:-(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t21sm2044741ejr.68 - gsmtp')

"Connection unexpectedly closed" error while sending email using SES from AWS

So I'm trying to send an email to my self using SMTP and AWS. The email I'm using on my configuration is verified since I'm still using sandbox mode in SES. While running the script I keep getting the error Connection unexpectedly closed even dough I tried to connect with OpenSSL and it connected but it showed a Didn't find STARTTLS in server response, trying anyway... error after connecting.
Here is my code:
MAIL = {}
MAIL['USERNAME'] = 'AKIAXARHTFGFKCDAO7PD'
MAIL['PASSWORD'] = 'BE0tXPq8wteiKZYtgD2TgtfFTGhgFGOhUp3F0lG0uqn'
MAIL['HOST'] = 'email-smtp.eu-central-1.amazonaws.com'
MAIL['PORT'] = 465
# Set user code
code = random.randrange(000000, 999999)
# Send email to user
print(code)
print(current_user.email)
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Ruby - Verification code'
msg['From'] = 'amng835#gmail.com'
msg['To'] = current_user.email
msg.attach(MIMEText(f'Your verification code is: {code}', 'plain'))
try:
server = smtplib.SMTP(MAIL['HOST'], MAIL['PORT'])
server.ehlo()
server.starttls()
server.ehlo()
server.login(MAIL('MAIL_USERNAME'), MAIL('MAIL_PASSWORD'))
server.sendmail('amng835#gmail.com', current_user.email, msg.as_string())
server.close()
except Exception as error:
print('Failed to send message to user')
print(error)
OpenSSL output:
The command:
openssl s_client -connect email-smtp.eu-central-1.amazonaws.com:465 -starttls smtp
The output:
CONNECTED(00000005)
Didn't find STARTTLS in server response, trying anyway...
write:errno=0
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 372 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
My documentation source:
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-smtp.html
There seems to have some issue with port 465.Change the code to below and it will work fine.
MAIL['PORT'] = 587

How to send an email without login to server in Python

I want to send an email without login to server in Python. I am using Python 3.6.
I tried some code but received an error. Here is my Code :
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)
server.sendmail(fromAddr, toAddr, text)
server.quit()
I expect the mail should be sent without asking user id and password but getting an error :
"smtplib.SMTPSenderRefused: (530, b'5.7.1 Client was not authenticated', 'from#Address.com')"
I am using like this. It's work to me in my private SMTP server.
import smtplib
host = "server.smtp.com"
server = smtplib.SMTP(host)
FROM = "testpython#test.com"
TO = "bla#test.com"
MSG = "Subject: Test email python\n\nBody of your message!"
server.sendmail(FROM, TO, MSG)
server.quit()
print ("Email Send")
import win32com.client as win32
outlook=win32.Dispatch('outlook.application')
mail=outlook.CreateItem(0)
mail.To='To address'
mail.Subject='Message subject'
mail.Body='Message body'
mail.HTMLBody='<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment="Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
The code below worked for me.
First, I opened/enabled Port 25 through Network Team and used it in the program.
import smtplib
smtpServer='smtp.yourdomain.com'
fromAddr='from#Address.com'
toAddr='to#Address.com'
text= "This is a test of sending email from within Python."
server = smtplib.SMTP(smtpServer,25)
server.ehlo()
server.starttls()
server.sendmail(fromAddr, toAddr, text)
server.quit()
First, you have to have a SMTP server to send an email. When you don't have one, usually outlook's server is used. But outlook only accepts authenticated users, so if you don't want to login into the server, you have to pick a server that doesn't need authentication.
A second approach is to setup an internal SMTP server. After you setup the internal SMTP server, you can use the "localhost" as the server to send the email. Like this:
import smtplib
receiver = 'someonesEmail#hisDomain.com'
sender = 'yourEmail#yourDomain.com'
smtp = smtplib.SMTP('localhost')
subject = 'test'
body = 'testing plain text message'
msg = 'subject: ' + subject + ' \n\n' + body
smtp.sendmail('sender', receiver, msg)

Resources