Guitar Geek
Guitar Geek

Reputation: 1

Issue Automating Email with O365

I have tried 3 different ways to use Python to automate email, and all three are giving different errors. Our company has a corporate Office 365 account - this "might" be part of the issue. It seems with each way, I'm getting closer. But I'm still missing something, and I'm not sure at this point what it is. Please assist if you can, and thank you in advance.

Way #1:

def send_email():
    try:
        # Create message container - the correct MIME type is multipart/alternative.
        msg = MIMEMultipart('alternative')

        msg['From'] = mail_from
        msg['To'] = mail_to
        msg['Subject'] = mail_subject

        # see the code below to use template as body
        body_text = mail_body_text
        body_html = mail_body_html

        # Create the body of the message (a plain-text and an HTML version).
        # Record the MIME types of both parts - text/plain and text/html.
        part1 = MIMEText(body_text, 'plain')
        part2 = MIMEText(body_html, 'html')

        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        msg.attach(part1)
        msg.attach(part2)

        # Send the message via local SMTP server.

        mail = smtplib.SMTP("smtp.outlook.office365.com", 587, timeout=20)

        # if tls = True
        mail.starttls()

        recepient = [mail_to]

        mail.login(username, __password)
        mail.sendmail(mail_from, recepient, msg.as_string())
        mail.quit()

    except Exception as e:
        raise e

Error:

smtplib.SMTPAuthenticationError: (535, b'5.7.139 Authentication unsuccessful, the user credentials were incorrect. [MN2PR11CA0027.namprd11.prod.outlook.com]')

Way #2: I went with the Python package, O365...

def maybe_this():
    credentials = (username, __password)
    account = Account(credentials)  #Account object from O365.Account.
    m = account.new_message()
    m.to.add(mail_to)
    m.subject = mail_subject
    m.body = mail_body_html
    m.send()

Error:

RuntimeError: No auth token found. Authentication Flow needed

Way #3: Researching the previous RunTimeError, I came up with this...

def maybe_that():
    # SPOILER ALERT: It doesn't frigging work.
    credentials = (username, __password)
    my_auth_flow_type = 'public'
    my_token_path = '(path to my python package)'
    my_token_backend = 'my_token.txt'
    account = Account(credentials, auth_flow_type=my_auth_flow_type, token_path=my_token_path, token_backend=my_token_backend)
    m = account.new_message()
    m.to.add(mail_to)
    m.subject = mail_subject
    m.body = mail_body_html
    m.send()

Error:

ValueError: Provide client id only for public flow credentials

Upvotes: 0

Views: 333

Answers (0)

Related Questions