달나라 노트

Python smtplib : smtplib를 이용하여 mail 보내기 1 본문

Python/Python smtplib

Python smtplib : smtplib를 이용하여 mail 보내기 1

CosmosProject 2021. 6. 26. 04:19
728x90
반응형

 

 

 

 

 

 

 

 

Python의 smtplib를 이용하면 mail을 보낼 수 있습니다.

 

예시 코드는 아래와 같습니다.

 

 

 

 

먼저 gmail을 이용한 예시입니다.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


sender = 'sender@gmail.com'
sender_pw = 'password'
recipient = 'recipient@gmail.com'
list_cc = ['cc1@gmail.com', 'cc2@naver.com']
str_cc = ','.join(list_cc)

title = 'Test mail'
contents = '''
This is test mail
using smtplib.
'''


smtp_server = smtplib.SMTP( # 1
    host='smtp.gmail.com',
    port=587
)

smtp_server.ehlo() # 2
smtp_server.starttls() # 2
smtp_server.ehlo() # 2
smtp_server.login(sender, sender_pw) # 3

msg = MIMEMultipart() # 4
msg['From'] = sender # 5
msg['To'] = recipient # 5
msg['Cc'] = str_cc # 5
msg['Subject'] = contents # 5
msg.attach(MIMEText(contents, 'plain')) # 6

smtp_server.send_message(msg) # 7
smtp_server.quit() # 8

 

1. smtplib를 이용하여 smtp server에 접근합니다.

이때 gmail의 host와 port를 명시해줘야하는데 예시에 있는 값을 참고하면 됩니다.

 

gmail에서 제공하는 공식 가이드는 다음과 같습니다.

https://support.google.com/mail/answer/7104828?hl=ko 

 

POP를 사용하여 다른 이메일 클라이언트에서 Gmail 메일 읽기 - Gmail 고객센터

도움이 되었나요? 어떻게 하면 개선할 수 있을까요? 예아니요

support.google.com

 

참고로 outlook의 setting값은 다음과 같습니다.

host = 'smtp.office365.com'
port=465

 

 

 

2. starttls를 시작하기 전 후에 ehlo를 선언해줍니다.

 

3. login을 합니다.

 

4. MIMEMultipart class를 생성합니다.

 

5. 4에서 생성한 MIMEMultipart 객체에 보내는 이메일, 받는 이메일, 메일 제목, 참조(cc) 등을 추가해줍니다.

 

6. 메일 본문을 넣어줍니다.

 

7. mail을 보냅니다.

 

8. smtp server를 종료합니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형

'Python > Python smtplib' 카테고리의 다른 글

Python smtplib : smtplib를 이용하여 mail 보내기 2  (0) 2021.06.26
Comments