Knightman
Knightman

Reputation: 3

Launch desktop mail program and start a blank email with python

I am attempting to launch the local mail application, Outlook 365 on windows and Mail on MacOS, and start a blank email, with the (To: ) column filled in from a database query.

Ideally it would look something similar to:

def email_create():
     if MacOS:
        open Mail.App
        To: = [sql statement]
     if Windows
        open Outlook.application
        To: = [sql statement]

EDIT: With the help of @spYder below, I wanted to just post my final product that seems to work great. Thank you again @spYder.

import webbrowser

    def send_email_command():
        sql = "SELECT EMAIL_PRIMARY FROM USER_INFORMATION"
        cursor.execute(sql)
        results = ','.join([item for row in [list(i) for i in (cursor.fetchall())] for item in row]) # creates the comma separated list from my query
        webbrowser.open('mailto: ' + results, new=1)

For windows outlook you would just replace the ',' with ';' because of the way email addresses are separated. My last step now is I just need to figure out how to identify if the user is using MacOS or Windows.

Upvotes: 0

Views: 1868

Answers (1)

spYder
spYder

Reputation: 317

If you really need to open Outlook, Maybe this would be a duplicate of Opening Outlook with Python

os.startfile("outlook")

For macOS :

        subprocess.call(["open", filename])

On the other hand, if just sending the email helps, check smtplib.

To start a blank message use the following:

import webbrowser
webbrowser.open('mailto:', new=1)

To write your email you can use smtplib ( as mentioned above ) + check : https://realpython.com/python-send-email/#sending-a-plain-text-email

Step 1 :

import smtplib, ssl

port = 465  # For SSL
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:

server.login("[email protected]", password)
# TODO: Send email here

Step 2 :

server.sendmail(sender_email, receiver_email, message)

sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here

Upvotes: 1

Related Questions