Envoyer Un E-Mail Outlook Via Python?

j'utilise Outlook 2003.

Quelle est la meilleure façon d'envoyer un courriel (par Outlook 2003) à l'aide de Python?

37
demandé sur user3262424 2011-06-13 19:31:43

8 réponses

utilisez la smtplib qui vient avec python. Notez que cela exigera que votre compte email autorise smtp, qui n'est pas nécessairement activé par défaut.

SERVER = "your.mail.server"
FROM = "yourEmail@yourAddress.com"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: cet exemple utilise un message fictif de google à un autre message de google

SERVER = "smtp.google.com"
FROM = "johnDoe@gmail.com"
TO = ["JaneDoe@gmail.com"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp in google."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

Pour que cela fonctionne, M. Doe besoin d'aller dans l'onglet options dans gmail et le configurer pour autoriser les connexions smtp. Notez l'ajout de la ligne de connexion pour s'authentifier sur le serveur distant. Original la version n'inclut pas ceci, un oubli de ma part.

13
répondu Spencer Rathbun 2016-03-09 17:03:12
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()

utilisera votre compte outlook local pour envoyer.

Remarque: si vous essayez de faire quelque chose de pas mentionné ci-dessus, regardez les COM docs propriétés/méthodes: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. Dans le code ci-dessus, mail est un objet MailItem.

63
répondu TheoretiCAL 2018-03-09 17:56:25

Vérifier via Google, il y a beaucoup d'exemples, voir ici pour un.

Inline pour faciliter la visualisation:

import win32com.client

def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
    s = win32com.client.Dispatch("Mapi.Session")
    o = win32com.client.Dispatch("Outlook.Application")
    s.Logon(profilename)

    Msg = o.CreateItem(0)
    Msg.To = recipient

    Msg.CC = "moreaddresses here"
    Msg.BCC = "address"

    Msg.Subject = subject
    Msg.Body = text

    attachment1 = "Path to attachment no. 1"
    attachment2 = "Path to attachment no. 2"
    Msg.Attachments.Add(attachment1)
    Msg.Attachments.Add(attachment2)

    Msg.Send()
26
répondu Steve Townsend 2011-06-13 15:35:35

en utilisant pywin32:

from win32com.client import Dispatch

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nUserName');
msg = session.Outbox.Messages.Add('Hello', 'This is a test')
msg.Recipients.Add('Corey', 'SMTP:corey@foo.com')
msg.Send()
session.Logoff()
6
répondu Corey Goldberg 2011-06-13 15:49:44

je voulais envoyer des e-mails en utilisant SMTPLIB, c'est plus facile et cela ne nécessite pas de configuration locale. Après d'autres réponses n'étaient pas directement utile, C'est ce que j'ai fait.

ouvrez Outlook dans un navigateur; allez dans le coin supérieur droit, cliquez sur l'icône de vitesse pour les paramètres, choisissez "Options" dans la liste déroulante qui apparaît. Allez à "Comptes", cliquez sur "Pop et Imap", Vous verrez l'option: "Laissez les appareils et les applications utiliser pop",

choisissez L'option Oui et sauvegardez les modifications.

Voici le code là après; éditer où nécessaire. La chose la plus importante est d'activer POP et le code du serveur ici;

import smtplib

body = 'Subject: Subject Here .\nDear ContactName, \n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Innitials'
try:
    smtpObj = smtplib.SMTP('smtp-mail.outlook.com', 587)
except Exception as e:
    print(e)
    smtpObj = smtplib.SMTP_SSL('smtp-mail.outlook.com', 465)
#type(smtpObj) 
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('me@outlook.com', "password") 
smtpObj.sendmail('sender@outlook.com', 'recipient@gmail.com', body) # Or recipient@outlook

smtpObj.quit()
pass
0
répondu simic0de 2017-07-22 18:38:42

autre que win32, si votre entreprise vous avait installé Web outlook, vous pouvez également essayer Python REST API, qui est officiellement fait par Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)

0
répondu LinconFive 2017-10-12 05:59:48

C'est celui que J'ai essayé D'utiliser Win32:

import win32com.client as win32
import psutil
import os
import subprocess
import sys

# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():


    outlook = win32.Dispatch('outlook.application')
    olFormatHTML = 2
    olFormatPlain = 1
    olFormatRichText = 3
    olFormatUnspecified = 0
    olMailItem = 0x0

    newMail = outlook.CreateItem(olMailItem)
    newMail.Subject = sys.argv[1]
    #newMail.Subject = "check"
    newMail.BodyFormat = olFormatHTML    #or olFormatRichText or olFormatPlain
    #newMail.HTMLBody = "test"
    newMail.HTMLBody = sys.argv[2]
    newMail.To = "xyz@abc.com"
    attachment1 = sys.argv[3]
    attachment2 = sys.argv[4]
    newMail.Attachments.Add(attachment1)
    newMail.Attachments.Add(attachment2)

    newMail.display()
    # or just use this instead of .display() if you want to send immediately
    newMail.Send()





# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")     
#

# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == "OUTLOOK.EXE":
        flag = 1
        break
    else:
        flag = 0

if (flag == 1):
    send_notification()
else:
    open_outlook()
    send_notification()
0
répondu Ankita Raman 2018-01-03 07:21:18

la plus simple de toutes les solutions pour OFFICE 365:

from O365 import Message

html_template =     """ 
            <html>
            <head>
                <title></title>
            </head>
            <body>
                    {}
            </body>
            </html>
        """

final_html_data = html_template.format(df.to_html(index=False))

o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final)
m.sendMessage()

ici df est une base de données convertie en Table html, qui est injectée dans html_template

0
répondu Gil Baggio 2018-09-27 10:25:11