Python 工具方法 发送邮件

发送 exchangelib 邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, FileAttachment, Configuration, NTLM
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
# 此句用来消除ssl证书错误,exchange使用自签证书需加上
import logging
import urllib3
urllib3.disable_warnings()
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

logger = logging.getLogger(__name__)

class Mail:

def __init__(self, email, password, host, port, retry: int = 3, *args, **kwargs) -> None:
self.email = email
self.password = password
self.host = host
self.port = port

def send(self, to_user, title: str, content: str):
self.send_exchange_mail(to_user, title, content)


def send_exchange_mail(self, to, subject, content, _type="plain", filename=None, is_send=False):
if isinstance(to, str):
to = [to]
for t in to:
try:
if self.password:
cred = Credentials(self.email.split('@')[0], self.password)
else:
cred = None
config = Configuration(server=self.host, credentials=cred, auth_type=NTLM)
a = Account(
primary_smtp_address=self.email, config=config, autodiscover=False, access_type=DELEGATE
)

m = Message(
account=a,
folder=a.sent,
subject=subject,
body=HTMLBody(content),
to_recipients=[Mailbox(email_address=t)]
)
if filename:
with open(filename, 'rb') as f:
_content = f.read()
file_attach = FileAttachment(name=filename[filename.rfind('/')+1:], content=_content)
m.attach(file_attach)
m.send()
print("【%s】邮件发送成功" % subject)
return True
except Exception as e:
print(f"【%s】邮件发送失败,请检查信息\n{e}" % subject)
return False

if __name__ == '__main__':
"""
pip3 install exchangelib -i https://pypi.doubanio.com/simple/
"""
mail = Mail("username@email.com", "username", "email.com", 25)
mail.send_exchange_mail("touser@email", "测试消息", "测试消息通过abc")