通过Python发送Outlook电子邮件?

2024-04-16 23:48:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Outlook 2003

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


Tags: 电子邮件方式outlook
3条回答

有关使用outlook的解决方案,请参见下面的理论答案。

否则,请使用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连接。

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

通过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()
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 docs属性/方法:https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook。在上面的代码中,mail是一个MailItem对象。

相关问题 更多 >