import time
from urllib.request import urlopen
import smtplib
from email.mime.text import MIMEText
smtplib https://docs.python.org/ko/3/library/smtplib.html
smtplib — SMTP 프로토콜 클라이언트 — Python 3.10.0 문서
smtplib — SMTP 프로토콜 클라이언트 소스 코드: Lib/smtplib.py The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP
docs.python.org
Simple Mail Transfer Protocol의 약자로서 메일을 보내는데 사용되는 프로토콜
MIME https://ko.wikipedia.org/wiki/MIME
MIME - 위키백과, 우리 모두의 백과사전
MIME(영어: Multipurpose Internet Mail Extensions)는 전자 우편을 위한 인터넷 표준 포맷이다. 전자우편은 7비트 ASCII 문자를 사용하여 전송되기 때문에, 8비트 이상의 코드를 사용하는 문자나 이진 파일들
ko.wikipedia.org
Multipurpose Internet Mail Extensions의 약자로 전자우편의 데이터 형식을 정의한 표준 포맷
def sendMail(sender, receiver, msg):
# 보내는 계정(gmail) 로그인
smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465) # port465 고정
smtp.login(sender, {password})
msg = MIMEText(msg)
msg['Subject'] = 'Send Email Success' # MIME 제목
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
sender = 'juranlim0422@gmail.com'
receiver = 'ijo0r98@naver.com'
msg = 'Hello!'
sendMail(sender, receiver, msg)
라이브러리
import smtplib # SMTP
from email.message import EmailMessage # MIME
import imghdr # 이미지
import re # 정규표현식
SMTP 서버 연결 (gmail)
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 465 # gmail 지정
이메일 유효성 검사 후 메일 전송
def sendEmail(addr):
# 이메일 유효성 검사
reg = "^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$"
if bool(re.mateh(reg, addr)): # 내용이 있으면 true, 내용이 없다면 false
# 메일 전송
smtp.send_message(message) # send_message(메일 내용)
print("정상적으로 메일이 발송되었습니다.")
else:
print("유효한 이메일 주소가 아닙니다.")
메일 내용 MIME 생성
message = EmailMessage() # 메시지를 이메일 형태로 만들어줌
message.set_content("메일 본문") # 본문 내용
message["Subject"] = "제목" # 메일 제목
message["From"] = "from@gmail.com" # 보내는이
message["To"] = "to@gmail.com" # 받는이
이미지 파일 첨부
# 이미지 파일 open
with open("image.png", "rb") as image:
image_file = image.read() # 읽어온 이미지 파일을 변수로 담음
# 이미지 확장자
image_type = imghdr.what('image', image_file)
print(image_type) # png
# multipart/mixed 타입의 메일 (사진 첨부)
# add_attachment(image, maintype, subtype(확장자))
message.add_attachment(image_file, maintype='image', subtype=image_type)
서버 연결 후 로그인
# smtplib.SMTP(SMTP_SERVER, SMTP_PORT) -> 에러; gmail SSL 처리 필수
smtp = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) # SMTP(서버주소, port)
# 메일 서버 로그인
email = "email@gmail.com"
password = "password"
smtp.login(email, password)
메일 전송 메서드(앞에서 정의한) 실행
sendEmail("to@gmail.com")
종료
smtp.quit()
[DJANGO] 파이썬의 list 자바스크립트에서 array로 받기 (0) | 2021.08.12 |
---|---|
[PYTHON] pickle(.pkl) 데이터 저장 및 불러오기 (0) | 2021.07.16 |
[PYTHON] requests 모듈 이용한 HTTP GET/POST 요청 (0) | 2021.06.28 |
[PYTHON] 파이썬 PANDAS 라이브러리 메서드 (0) | 2021.06.19 |
[PYTHON] 예외처리(Exception) (0) | 2021.06.14 |
댓글 영역