通过 Python 发送 Outlook 电子邮件?

发布于 2024-11-15 02:51:31 字数 116 浏览 2 评论 0原文

我正在使用 Outlook 2003

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

I am using Outlook 2003.

What is the best way to send email (through Outlook 2003) using Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

网名女生简单气质 2024-11-22 02:51:31
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 对象。

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

Will use your local outlook account to send.

Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail is a MailItem Object.

清风夜微凉 2024-11-22 02:51:31

有关使用 Outlook 的解决方案,请参阅TheoretiCAL 的答案

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

SERVER = "smtp.example.com"
FROM = "[email protected]"
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 = "[email protected]"
TO = ["[email protected]"] # 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()

< sub>要真正与 gmail 配合使用,Doe 先生需要转到 gmail 中的选项选项卡并将其设置为允许 smtp 连接。

请注意添加的登录行以对远程服务器进行身份验证。最初的版本不包括这一点,这是我的疏忽。

For a solution that uses outlook see TheoretiCAL's answer.

Otherwise, use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "[email protected]"
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: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "[email protected]"
TO = ["[email protected]"] # 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()

For it to actually work with gmail, Mr. Doe will need to go to the options tab in gmail and set it to allow smtp connections.

Note the addition of the login line to authenticate to the remote server. The original version does not include this, an oversight on my part.

泪痕残 2024-11-22 02:51:31

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

在浏览器中打开 Outlook;转到右上角,单击“设置”的齿轮图标,从出现的下拉列表中选择“选项”。
转到“帐户”,单击“Pop 和 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('[email protected]', "password") 
smtpObj.sendmail('[email protected]', '[email protected]', body) # Or recipient@outlook

smtpObj.quit()
pass

I wanted to send email using SMTPLIB, its easier and it does not require local setup. After other answers were not directly helpful, This is what i did.

Open Outlook in a browser; Go to the top right corner, click the gear icon for Settings, Choose 'Options' from the appearing drop-down list.
Go to 'Accounts', click 'Pop and Imap',
You will see the option: "Let devices and apps use pop",

Choose Yes option and Save changes.

Here is the code there after; Edit where neccesary.
Most Important thing is to enable POP and the server code herein;

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('[email protected]', "password") 
smtpObj.sendmail('[email protected]', '[email protected]', body) # Or recipient@outlook

smtpObj.quit()
pass
兲鉂ぱ嘚淚 2024-11-22 02:51:31

使用 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:[email protected]')
msg.Send()
session.Logoff()

using 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:[email protected]')
msg.Send()
session.Logoff()
风为裳 2024-11-22 02:51:31

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

A simple solution for Office 365 is

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

Here df is a dataframe converted to an html Table, which is being injected into html_template

心如狂蝶 2024-11-22 02:51:31

这是一个很老的问题,但还有一个解决方案。当前的 Outlook SMTP 服务器是(截至 2022 年):

  • 主机:smtp.office365.com
  • 端口:587(对于 TLS)

也许最简单、最干净的解决方案是使用 < a href="https://pypi.org/project/redmail/" rel="noreferrer">Red Mail 已设置这些:

pip install redmail

然后:

from redmail import outlook

outlook.user_name = "[email protected]"
outlook.password = "<MY PASSWORD>"

outlook.send(
    receivers=["[email protected]"],
    subject="An example",
    text="Hi, this is an example."
)

Red Mail 支持各种高级功能:

链接:

免责声明:我是作者

This is a pretty old question but there is one more solution. The current Outlook SMTP server is (as of 2022):

  • Host: smtp.office365.com
  • Port: 587 (for TLS)

Probably the easiest and cleanest solution is to use Red Mail that has these already set:

pip install redmail

Then:

from redmail import outlook

outlook.user_name = "[email protected]"
outlook.password = "<MY PASSWORD>"

outlook.send(
    receivers=["[email protected]"],
    subject="An example",
    text="Hi, this is an example."
)

Red Mail supports all sorts of advanced features:

Links:

Disclaimer: I'm the author

小矜持 2024-11-22 02:51:31

这是我使用 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 = "[email protected]"
    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()

This was one I tried using 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 = "[email protected]"
    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()
落墨 2024-11-22 02:51:31

除了win32之外,如果你的公司设置了web Outlook,你也可以尝试PYTHON REST API,这是微软官方制作的。 (https://msdn.microsoft.com/en -us/office/office365/api/mail-rest-operations)

Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)

極樂鬼 2024-11-22 02:51:31
import pythoncom
import win32com.client

mail = win32com.client.Dispatch('outlook. Application', 
       pythoncom.CoInitialize())
ol_mail_item = 0x0
new_mail = mail.CreateItem(ol_mail_item)
import pythoncom
import win32com.client

mail = win32com.client.Dispatch('outlook. Application', 
       pythoncom.CoInitialize())
ol_mail_item = 0x0
new_mail = mail.CreateItem(ol_mail_item)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文