sending email from a company email using python code- facing authentication issue

Viewed 29

I am trying to implement a automated mail sending from a outlook account with python SMTP code. I am able to send a mail from a account which have the 2-Factor authentication turned-Off. But I need to send a mail from a account which have 2-Factor authentication with a OTP. I am facing an issue during authentication, If someone have an idea will be thankful.

import smtplib
from email.message import EmailMessage
from email.utils import formataddr
from pathlib import Path

PORT = 587  
EMAIL_SERVER = "smtp-mail.outlook.com"  # Adjust server address, if you are not using @outlook

sender_email = "user@company.com"
password_email = "password"


def send_email(subject, receiver_email, name):
    # Create the base text message.
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = formataddr(("USER", f"{sender_email}"))
    msg["To"] = receiver_email
    msg["BCC"] = sender_email

    msg.set_content('Hi, I hope you are well. I would be really grateful if you could confirm that everything is on track for Automation.')

    with smtplib.SMTP(EMAIL_SERVER, PORT) as server:
        server.starttls()
        server.login(sender_email, password_email)
        server.sendmail(sender_email, receiver_email, msg.as_string())
        
if __name__ == "__main__":
    send_email(
        subject="Python Automation",
        name="NAME",
        receiver_email="receiver@gmail.com",
    )
    print('Email Sent Success')

raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [PN2PR01CA0158.INDPRD01.PROD.OUTLOOK.COM]')

getting error - raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [PN2PR01CA0158.INDPRD01.PROD.OUTLOOK.COM]')

Is the error navigating to OTP authentication ? Is there any ways to bypass the OTP authentication.

As I am trying with a professional sender email ID, I have limited access to the admin rights to disable the SMTP-Authentication.

0 Answers
Related