authentication error trying to send Outlook email from Python - python-3.x

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:

Related

send mail using service account and google api python

Edit:
after accepting the answer:
my question was about a free Gmail account (I didn't know there was a difference) and the answer is about a paid account (and it is a currect one),
the answer showed me that there was a difference and it led me the correct answer to my situation - use a passcode
im trying to send mail using google API and service account, but I'm getting the following erre:
An error occurred: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/drafts?alt=json returned "Precondition check failed.". Details: "[{'message': 'Precondition check failed.', 'domain': 'global', 'reason': 'failedPrecondition'}]">
this is my code:
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.service_account import ServiceAccountCredentials
import base64
from email.message import EmailMessage
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://mail.google.com/']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
creds = ServiceAccountCredentials.from_json_keyfile_name(
"""path_to_cred_file.json""", SCOPES)
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
message = EmailMessage()
message.set_content('This is automated draft mail')
message['To'] = 'somemail#gmail.com'
message['From'] = 'somemail#gmail.com'
message['Subject'] = 'Automated draft'
# encoded message
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_message = {
'message': {
'raw': encoded_message
}
}
# pylint: disable=E1101
draft = service.users().drafts().create(userId="me",
body=create_message).execute()
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()
"Precondition check failed" usually means that you're trying to do something that cannot be done. In this case you're trying to send an email from a service account, which is not possible. This answer has a link to a relevant thread from the Google documentation. They say the following:
Service accounts dont work with gmail unless you set up domain wide delegation to a Gsuite account. The reason being is that a service account is its own user you need to delegate its permission to access your gmail account. This will only work with a gsuite domain email address.
This means that the service account by itself cannot send messages, but instead needs to be delegated access to a regular user account in order to send emails. To do this you can add the following line after your creds:
delegated_creds=credentials.with_subject("someuser#yourdomain.com")
#where someuser# is the email of the user that you're sending email as
After that you can use delegated_creds instead of creds to call the service.
Also, you seem to have gotten your sample from Google's guide, but note that your sample creates a draft instead of sending an email. The API call to send emails is a little different. With that in mind here's a complete example based on your code which worked for me:
#all the imports
SCOPES = ['https://mail.google.com/']
def main():
creds = None
creds = ServiceAccountCredentials.from_json_keyfile_name(
"""path_to_cred_file.json""", SCOPES)
delegated_creds=credentials.with_subject("someuser#yourdomain.com")
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=delegated_creds)
message = EmailMessage()
message.set_content('This is automated draft mail')
message['To'] = 'somemail#gmail.com'
message['From'] = 'somemail#gmail.com'
message['Subject'] = 'Automated draft'
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_message = {
'raw': encoded_message
}
email = service.users().messages().send(userId="me",
body=create_message).execute()
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()
Finally, as explained in the thread I linked, this only works for Google Workspace accounts and you cannot delegate access to free Gmail accounts, so keep that in mind.

how to send email with python after the google update?

I am using smtplib but after writing the code, been getting a bad credentials error and after changing email password and adding python to app passwords now i get a TimeoutError,
import smtplib
my_email = "ro21manrrereynolds349#gmail.com"
# password = "nqfpmxfgvrpunxku"
password = "6!OmRXMxLs8"
conn = smtplib.SMTP("smtp.gmail.com", port=465)
conn.ehlo()
conn.starttls()
conn.login(user=my_email, password=password)
conn.sendmail(
from_addr=my_email,
to_addrs="horisroman#gmail.com",
msg="Subject:Ola\n\nYou there."
)
conn.quit()
tried changing password, changing email, adding python to the app passwords, used email.mime.multipart but still got the same issues

How to fix SMTPNotSupportedError and SMTPAuthenticationError?

I want to send thousands of emails in python by using an open source SMTP server. I have to locally install an open source SMTP server on windows 10 that can send bulk emails , without any limit.
I have installed HMailServer on my windows 10 & configured it as a localhost, I have set a domain as "st.com" in HmailServer and created a account with that domain as "ammar#st.com". Now I have to send emails to user with that account. The list of Receivers emails are in .xlsx file (receivers email e.g. is like ammar#gmail.com)
import pandas as pd
import smtplib
SenderAddress = "ammar#st.com"
password = "123456789"
e = pd.read_excel("Email.xlsx")
emails = e['Emails'].values
server = smtplib.SMTP("localhost", 25)
#server.starttls()
#server.login(SenderAddress, password)
msg = "Hello this is a email form python"
subject = "Hello world"
body = "Subject: {}\n\n{}".format(subject,msg)
for email in emails:
server.sendmail(SenderAddress, email, body)
print("Sent")
server.quit()
After I run this program it gives "SMTPNotSupportedError: STARTTLS extension not supported by server." error and "SMTPAuthenticationError: (530, b'A SSL/TLS-connection is required for authentication.')".
Can anybody tell me how it works that I can send a email to list of users with HmailServer or any other server locally.

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)

Error in email-sending program in Python with smtplib

Here is my code:
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("MyEmail", "pass")
msg = "YOUR MESSAGE!"
server.sendmail("MyEmail", "MyEmail", msg)
server.quit()
The error message is the following:
Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14
What is the solution to my problem?
You need permissions, go to this link https://www.google.com/settings/security/lesssecureapps and allow the access

Resources