通过Python发送Outlook电子邮件?

时间:2011-06-13 15:31:44

标签: python outlook

我正在使用Outlook 2003

使用Outlook 2003发送电子邮件(通过Python)的最佳方式是什么?

8 个答案:

答案 0 :(得分:86)

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()

将使用您的本地Outlook帐户发送。

请注意,如果您尝试执行上面未提及的操作,请查看COM文档属性/方法:https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook。在上面的代码中,mail是一个MailItem对象。

答案 1 :(得分:27)

通过Google查看,有很多示例,请参阅here

内联易于查看:

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()

答案 2 :(得分:18)

使用python附带的smtplib。请注意,这将要求您的电子邮件帐户允许smtp,默认情况下不一定启用。

SERVER = "smtp.example.com"
FROM = "yourEmail@example.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()

编辑:此示例使用RFC2606

中所述的保留域
SERVER = "smtp.example.com"
FROM = "johnDoe@example.com"
TO = ["JaneDoe@example.com"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# 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()

为了实际使用gmail,Doe先生需要转到gmail中的选项选项卡并将其设置为允许smtp连接。

请注意添加登录行以对远程服务器进行身份验证。原始版本不包含此内容,这是我的疏忽。

答案 3 :(得分:6)

使用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()

答案 4 :(得分:1)

最简单的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()
  

此处 df 是转换为html表的数据框,该表将被注入html_template

答案 5 :(得分:0)

我想使用SMTPLIB发送电子邮件,它更容易,并且不需要本地设置。在其他答案没有直接帮助之后,这就是我所做的。

在浏览器中打开Outlook;转到右上角,单击设置的齿轮图标,从出现的下拉列表中选择“选项”。 转到“帐户”,点击“流行和Imap”, 您将看到选项:“让设备和应用程序使用pop”,

选择是选项并保存更改。

以下是那里的代码;编辑必要的地方。 最重要的是在此启用POP和服务器代码;

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

答案 6 :(得分:0)

除了win32之外,如果您的公司已经设置了您的Web Outlook,您还可以尝试由Microsoft正式制作的PYTHON REST API。 (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations

答案 7 :(得分:0)

这是我尝试使用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()