본문 바로가기
Programing/Toy Project

Outlook 메일 전송 Python

by yooom 2023. 6. 5.
import win32com.client
outlook = win32com.client.Dispatch('Outlook.Application')

mail_address_list = ['~~@naver.com','~~~~@gmail.com' ]  

send_mail = outlook.CreateItem(0)
for i in range (len(mail_address_list)):
    send_mail = outlook.CreateItem(0)
    send_mail.To = mail_address_list[i] # 메일 수신인
    send_mail.Subject = '메일 제목 뫄뫄 ' # 메일 제목
    send_mail.HTMLBody = '메일 내용 블라블라 '  # 메일 내용 (HTML 가능)
    send_mail.Send()

print('전송완료')

===================================================

약간 수정해서 파일첨부와 이미지첨부를 할 수 있도록 써봤다.

===================================================

# 같은 내용 이메일 일괄 전송

import io
import base64
from PIL import Image
import win32com.client

mail_address_list = ['~~~@naver.com', '~~~@gmail.com'] # 이메일 입력
subject = ' 사진 여러장 첨부 '  #  제목 입력

img_list = ['cat_image1.jpg','cat_image2.jpg']   # 이미지 위치, 이름
attachment = [r'C:\Users\leeyu\cat_image2.jpg',r'C:\Users\leeyu\cat_image3.jpg']   #첨부파일 절대위치, 이름

# 첨부 파일은 주소값을 그대로 반환하는 r을 앞에 적어줘야 함

texts ='''
<html>
<body>

이러이러하다<br/>
이 밑에 이미지 넣는다
<p>이렇게도 줄 바꿈 된다</p>

</body>
</html>
'''     

# 여러 줄 내용 입력, 글 마지막에 이미지가 들어간다


def send_mail(to,subject,text, attach=[]):
    new_Mail = win32com.client.Dispatch("Outlook.Application").CreateItem(0)
    new_Mail.To = to
    new_Mail.Subject = subject
    new_Mail.HTMLBody = text
    if attachment:
        for atch in attachment:
            new_Mail.Attachments.Add(atch)
    new_Mail.Send()
    
def attach_img(img_add):  
    img = Image.open(img_add)
    bytearr = io.BytesIO()
    img.save(bytearr, format="JPEG")
    imgbytearr = bytearr.getvalue()
    encoded_image = base64.b64encode(imgbytearr).decode("utf-8")
    image_attach = f'<img src="data:image/png;base64,{encoded_image}"/>'
    return image_attach

def main():
    global texts
    for i in range (len(mail_address_list)):  
        for j in range (len(img_list)):
            texts += attach_img(img_list[j])
        send_mail(mail_address_list[i], subject, texts)
        
if __name__ == '__main__':
    main()
    print('완료')
728x90

'Programing > Toy Project' 카테고리의 다른 글

엑셀 파일 요약  (0) 2023.06.02
당일 구글 기사 크롤링 with Python  (0) 2023.02.06
네이버 기사 키워드 크롤링 + 액셀 저장  (0) 2023.02.05

댓글