여친의 부탁으로 메일보내기 매크로를 작성했었다.
맥에서 작성해서 줬는데 윈도우의 인코딩 문제란 ㄷㄷㄷ
Ref : docs.python.org/3/library/email.examples.html
email: Examples — Python 3.9.4 documentation
Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages. First, let’s see how to create and send a simple text message (both the text content and the addresses may cont
docs.python.org
설정 환경
- 윈도우 계열 (윈도우7 / 10 에서 테스트함)
- python3
불필요한 import 가 많으므로 알아서 수정해서 쓸것..
예시 코드를 보면 여러 방법이 있는데 이게 젤 깔끔하게 메일이 가더라.
일부 코드는 삭제함.
코드
#-*- coding:utf-8 -*- # SendMail Macro Ver 0.1 - with Py3 import smtplib, io, mimetypes, os, sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from string import Template from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid my_Id = "아이디" my_Mail_Addr = "메일주소" # 예) gmail.com my_ID_Mail_Addr = my_Id + "@" + my_Mail_Addr my_Pwd = "비밀번호" my_Username = "보낼사람이름" # 이메일 앞에 이름 지정 attached_File = "첨부할파일명" # 첨부파일명 my_subject = "메일 제목" #제목 def read_template(filename): with io.open(filename, 'rt', encoding='utf-8') as template_file: template_file_content = template_file.read() return Template(template_file_content) def send_MyEmail( receive_Hangul_Name, receive_Email_Id, receive_Email_Addr, mail_body ): s = smtplib.SMTP_SSL(host="SMTP 주소", port='465') s.login(my_ID_Mail_Addr, my_Pwd) # EmailMessage 형태 # Ref : https://docs.python.org/3/library/email.examples.html msg = EmailMessage() msg['From'] = Address(my_Username, my_Id, my_Mail_Addr) msg['To'] = Address(receive_Hangul_Name, receive_Email_Id, receive_Email_Addr) msg['Subject'] = receive_Hangul_Name + my_subject asparagus_cid = make_msgid() msg.add_alternative(mail_body.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html') ## 첨부파일 path = os.path.join('.', attached_File) ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=attached_File) s.send_message(msg) def main(): with open('list.txt', 'r', encoding='UTF8') as fp: receiver = fp.readlines() for line in receiver: receive_Hangul_Name = "보낼사람 이름" receive_Email_Id = "보낼사람 메일 ID" receive_Email_Addr = "보낼사람 메일 주소" # 보낼 내용은 for_send_msg.html 파일에 HTML 형태로 작성해 둘 것. mail_body = read_template('for_send_msg.html').substitute() # substitute 뭐하는 놈이지? send_MyEmail( receive_Hangul_Name, receive_Email_Id, receive_Email_Addr, mail_body ) if os.path.isfile(for_send_msg_file): os.remove(for_send_msg_file) if __name__ == '__main__': main() |