python發送郵件帶附件


Exchange發送郵件

config.email_url :郵箱服務地址
config.email_user :賬戶
config.email_pas:密碼

import config
import os
from exchangelib import DELEGATE, Account,Credentials,Configuration,NTLM,Message,Mailbox,HTMLBody,FileAttachment
from exchangelib.protocol import BaseProtocol,NoVerifyHTTPAdapter

BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
cred = Credentials(config.email_user,config.email_pass)
con = Configuration(server=config.email_url,credentials=cred,auth_type=NTLM)
account = Account(primary_smtp_address=config.email_user, config=con,autodiscover=False,access_type=DELEGATE)

class Mail():
    def __init__(self,to_list,sub,content,attach_list=[]):
        self.to_list = to_list
        self.sub = sub
        self.content = content
        self.attach_list = attach_list

    def send_mail(self):
        #mail_host = "smtp.126.com"
        to_list = []
        for address in self.to_list:
            to_list.append(Mailbox(email_address=address))
        try:
            m = Message(account=account,folder=account.sent,subject=self.sub,body=self.content,to_recipients=to_list)
            if self.attach_list:
                for fpath in self.attach_list:
                    if not os.path.isfile(fpath):
                        continue
                    with open(fpath,'rb') as f:
                        cont = f.read()
                    name = os.path.basename(fpath)
                    attachf = FileAttachment(name=name,content=cont)
                    m.attach(attachf)
            m.send_and_save()
            return True,'success'
        except Exception as e:
            return False,str(e)

if __name__=='__main__':
    content = '''郵件發送 測試'''
    mail = Mail(['mrhusong@126.com'],"測試",content)
    print(mail.send_mail())

163郵箱發送郵件

https://www.cnblogs.com/xiaodai12138/p/10483158.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM