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 对象。
有关使用 Outlook 的解决方案,请参阅 TheoretiCAL's answer。
否则,使用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 连接。
请注意添加登录行以对远程服务器进行身份验证。原始版本不包含此内容,这是我的疏忽。
smtp
服务器与我的电子邮件不同 - 因此,即使我使用不同的电子邮件地址(不是att's
) 发送电子邮件。 Outlook
已配置为处理此问题。如果有其他解决方案(不基于 Outlook
)也支持这一点,我很乐意听取建议。
通过 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()
alert message
,询问我是要继续还是终止访问脚本。有没有办法跳过这个alert message
?
outlook
并且它可能是病毒等,如果我想继续。
win32
模块的 Mac OS 上做同样的事情?
我想使用 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('me@outlook.com', "password")
smtpObj.sendmail('sender@outlook.com', 'recipient@gmail.com', body) # Or recipient@outlook
smtpObj.quit()
pass
使用 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()
outlook
错误消息吗?
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
这是一个很老的问题,但还有一个解决方案。当前的 Outlook SMTP 服务器是(截至 2022 年):
主机:smtp.office365.com
端口:587(用于 TLS)
可能最简单和最干净的解决方案是使用已设置这些的 Red Mail:
pip install redmail
然后:
from redmail import outlook
outlook.user_name = "example@hotmail.com"
outlook.password = "<MY PASSWORD>"
outlook.send(
receivers=["you@example.com"],
subject="An example",
text="Hi, this is an example."
)
Red Mail 支持各种高级功能:
HTML 和文本正文
各种类型的附件
嵌入图像
它也有 Jinja 支持
链接:
文档:https://red-mail.readthedocs.io/en/latest/
源代码:https://github.com/Miksus/red-mail
免责声明:我是作者
除了win32,如果你的公司已经为你设置了web outlook,你也可以试试微软官方制作的PYTHON REST API。 (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)
这是我尝试使用 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()
mail.To = "a@b.com;c@d.com"
中简单地用冒号分隔的电子邮件字符串,让我知道它是否有效