새소식

Programming/python

[python3] smtp 로 여러명에게 이메일 보내기

  • -

삽질을 거듭하다가 기록용으로 남깁니다.

def smtphandler(self):
        smtp = None
        mailconfig = self.config['primaryServer']
        if not mailconfig['server'] or not mailconfig['port'] or not mailconfig['uid'] or not mailconfig['pw'] or not mailconfig['sender']:
            mailconfig = self.config['secondaryServer']
        if 'smtp/starttls':
            smtp = smtplib.SMTP('smtp.gmail.com', 587)
        elif 'ssl/tls':
            smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        try:
            if 'smtp/starttls':
                print(f'\tSay hello to {mailconfig["server"]}')
                smtp.ehlo()
                print(f'\tStarting TLS...')
                smtp.starttls()
            print('\tTries to log in...')
            smtp.login('s@gmail.com', 'gmail_password')
        except smtplib.SMTPException as e:
            print (f'Error: unable to connect to email server smtp.gmail.com:587...{e}')
            pass
        except Exception as e:
            print(f"Unknown error: {e}")
        msg = MIMEText('real content'.encode('utf-8'), _charset='UTF-8')
        msg['Subject'] = 'test subject'
        msg['To'] = 'b@gmail.com, c@gmail.com, d@gmail.com'
        try:
            smtp.sendmail('s@gmail.com', msg['To'].split(','), msg.as_string())
        except smtplib.SMTPException as e:
            print(f"Error: failed to send message {msg.as_string()} to smtp.gmail.com")
        print ('\tSending email is done!')
        smtp.quit()

뭔가 코드가 길고 복잡해 보이는데 핵심은 msg['To'] 와 smtp.sendmail() 함수의 두번째 인수인 msg['To'].split(',') 입니다.
msg 는 일반 텍스트 형태로 To를 포함하고 있어야 하고, sendmail() 함수의 두번째 인수 자리에는 리스트가 들어가야 합니다.

이걸 캐치 못해서 한참을 고생했네요. 누군가에겐 도움이 되시길...

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.