python通过代理服务器后面的ms交换服务器发送邮件

时间:2019-01-23 06:47:55

标签: python email outlook exchange-server exchangelib

对于我的机器,登录Windows系统后,Outlook将使用匿名身份验证自动登录。

Outlook使用HTTP连接到Microsoft Exchange,并且仅使用SSL连接。

Microsoft Exchange服务器是

code@ms.exchange.server

连接到代理服务器时,证书中的主体名称是已知的。

Header:email.server.sample

连接到我的Exchange代理服务器的URL是已知的。

https://email.server.sample

连接到Exchange的代理服务器时使用“协商身份验证”。

现在,问题是,python如何在这种情况下发送电子邮件?

1 个答案:

答案 0 :(得分:0)

这是我为这种情况所做的,希望对您也有用:

请参阅此页面以获取文档:

Documentation for outlook object

import numpy as np
import pandas as pd
import re
import datetime
from dateutil.relativedelta import relativedelta
import win32com.client as win32
import tldextract
outlook = win32.Dispatch('outlook.application')
import win32com.client 
from win32com.mapi import mapitags
# outlook = win32com.client.Dispatch("Outlook")
outlook_app = win32com.client.Dispatch("Outlook.Application")
MAPI = outlook_app.GetNamespace("MAPI")

inbox = MAPI.GetDefaultFolder(6)

def send_email(To,cc_list = "",
             bcc_list = "", subject = "", htmlbody = ""):
    mail = outlook.CreateItem(0)
    mail.To = To
    mail.cc = cc_list
    mail.Bcc = bcc_list
    mail.Subject = subject
    mail.HTMLBody = htmlbody 
    mail.Send()

def move_and_save_attachments_for_all_inbox_emails():
    done = False
    while(not done):
        counter = 0
        for mail in inbox.Items:
            if(mail.Class == 43):
                counter += 1
                save_current_email_attachments(mail)
                move_current_email(mail)
        if counter == 0:
            done = True

def move_current_email(mail):
    if(mail.Class==43):
        if(mail.SenderEmailType=='EX'):
            sender = mail.Sender.GetExchangeUser().PrimarySmtpAddress
        else:
            sender = mail.SenderEmailAddress
        domainname = tldextract.extract(sender).domain
        try:
            mail.Move(inbox.Folders[domainname.upper()])
        except:
            inbox.Folders.add(domainname.upper())
            mail.Move(inbox.Folders[domainname.upper()])

def save_current_email_attachments(mail):
    if(mail.Class==43):
        if(mail.SenderEmailType=='EX'):
            sender = mail.Sender.GetExchangeUser().PrimarySmtpAddress
        else:
            sender = mail.SenderEmailAddress
        username, domainname = sender.split('@')
        for attachment in mail.Attachments:
            attachment.SaveAsFile('attachments\\'+domainname+'_'+attachment.Filename)

def move_all_mails_into_inbox():
    done = False
    while(not done):
        counter = 0
        for folder in inbox.folders:
            for mail in folder.Items:
                counter += 1
                mail.Move(inbox)
        if(counter == 0):
            done = True