Python

[Python] Mail CC 추가

비번변경 2022. 2. 18. 20:39

2021.06.21 - Python 첨부 파일 메일 전송 

 

Python 첨부 파일 메일 전송

2021.06.20 - Python 텍스트 메일 전송 지난 글에 이어 이 글에서는 첨부파일을 포함한 메일을 전송할 수 있는 코드를 다룬다. 마찬가지로 코드 전체를 복사해서 사용한다면, MAIN 아래의 email_sender부터

passwd.tistory.com

Mail 송신 시 참조 수신자를 추가해야 하는 필요성이 생겨서, 위 글 이후로 아주 오랜만에 Mail 관련으로 정리한다. 이전 글의 코드에서 수정한 부분만을 정리해둔다.

 

방법

1. 참조 수신자 목록을 메세지 헤더에 추가한다.

각 메일 주소는 ,(쉼표)로 구분되어야 한다. 이 글에서는 참조 수신자 목록을 List로 초기화할 것이기 때문에 join 함수를 사용해 문자열로 변환했다.

    def write(self, exist_attachment, attachment_filepath):
        self.msg['From'] = self.sender
        self.msg['To'] = ",".join(self.recipient)
        self.msg['Cc'] = ",".join(self.email_cc)
        self.msg['Subject'] = self.subject

        self.msg.attach(MIMEText(self.body, 'plain'))
        self.attachment(exist_attachment, attachment_filepath)

추가로 여러 명을 수신자로 설정할 수 있도록, 수신자 목록도 문자열에서 문자열 리스트로 변경할 것이다. 수신자도 join 함수를 이용해 문자열로 변환하도록 한다.

 

2. 수신자와 참조 수신자 목록 전부 smtp.sendmail 호출 시 to_addr 매개변수로 전달한다.

리스트 형 데이터로 전달하면 된다.

    def send(self, login=False):
        recipients_list = self.recipient + self.email_cc
        server = smtplib.SMTP(self.email_server, self.email_server_port)
        server.ehlo()
        if login:
            server.starttls()
            server.login(self.sender, self.passwd)
            
        # smtp.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
        server.sendmail(self.sender, recipients_list, self.msg.as_string())
        server.quit()

참고로 숨은 참조(BCC)의 경우에는 메시지 헤더에 Bcc를 추가하지 않고, smtp.sendmail에 to_addr로만 메일 주소를 전달하면 된다고 한다.

 

3. CC 메일 주소 선언

메일 송신자, 수신자 등의 정보 초기화 시 참조 수신자도 함께 초기화하도록 한다.

여러 명을 수신자로 설정할 수 있도록, 수신자 목록도 문자열에서 문자열 리스트로 변경하였다.

# sender/recipient info
email_sender = 'exampleh@example.com'
sender_passwd = 'PASSWD'
email_recipient = ['exampleh@example.com']
email_cc = ['exampleh@example.com', 'exampleh@example.com']
email_server = 'smtp.gmail.com'
email_server_port = 587

 

이 글의 코드는 https://github.com/jinyuo/mail_python로 공개해두었다. 

 


참고 문서

https://stackoverflow.com/questions/1546367/python-how-to-send-mail-with-to-cc-and-bcc

 

python: how to send mail with TO, CC and BCC?

I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO

stackoverflow.com

참고 문서에 따르면 smtp.sendmail()이 아닌, smtp.send_message를 사용하는 방법이 있다고 한다. 이 방법은 확인하고 정리해볼 예정이다.

728x90