Search code examples
pythonemailpyqtattachmentemail-attachments

Directing to Default Mail App with Attachment Python


I have been trying to direct the user to the default mail app on pc (or have the user select the mailing app they want) then open the app to send a mail with an attachment already included.

I tried mailto and webbrowser explained here: Python: launch default mail client on the system They work but it is not possible to add attachments automaticaly by these methods anymore. I read it is removed due to some safety issues. Or maybe I could not find how to do that.

I managed achieving what I wanted by using pywin32 with outlook. But it requires the user to have outlook on their pc and not everyone has that.

I dont wanna use something like smtplib, I just want to use whatever mail app there is on the user's PC or possibly somehow direct them to gmail by using chrome or whatever. I want the user to enter their own passwords to the directed app if they were not already logged in. Cannot put any type of passwords into the code.

I could not find any solutions aside from using outlook which is limiting. Is there anything I can do?


Solution

  • On Windows you can compose an email draft in MIME format and write it into an .eml file with all the attachments needed. Then, use os.startfile to launch the default application for handling email draft.

    On Linux, where os.startfile() is not available, there is a widely available tool xdg-email. You can launch it with subprocess:

    import subprocess
    subprocess.run(["xdg-email", "--attach", "1.png", "[email protected]"])
    

    It however, does not implement any standard interface, but tries to guess the application to launch and supports each of them case-by-case: https://github.com/freedesktop/xdg-utils/blob/8ae02631a9806da11b34cd6b274af02d28aee5da/scripts/xdg-email.in

    You can also implement the same logic manually, detect the program to start heuristically and start at least Outlook or Thunderbird. Thunderbird has a command line interface to create emails with attachments with thunderbird -compose "[email protected],attachment=....