SMTP로 이메일을 발송할 일이 종종 있다.
물론 이미지 태그 <img>를 사용하여 어딘가에 저장된 사진을 html 형식으로 전송해도 되지만,
경우에 따라서는 그냥 해당 이메일에 첨부하는게 제일 좋은 때가 있다.
어떤 백엔드 언어를 사용해도 무방하겠지만,
가독성이 좋은 python의 smtplib를 통해서 알아보자.
첨부파일이 없다면 그냥 아래와 같이 해도 무방하겠다.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 발송 계정 정보
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_email_password'
# 수신자 이메일 주소
to_email = 'recipient@example.com'
# 이메일 제목과 내용
subject = '이메일 제목'
body = '이메일 내용'
# MIMEText를 사용하여 이메일 메시지 설정
message = MIMEMultipart()
message['From'] = smtp_username
message['To'] = to_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
# SMTP 서버에 연결
with smtplib.SMTP(smtp_server, smtp_port) as server:
# 연결 보안 설정 (TLS 사용)
server.starttls()
# 로그인
server.login(smtp_username, smtp_password)
# 이메일 발송
server.sendmail(smtp_username, to_email, message.as_string())
print('이메일이 발송되었습니다.')
이미지 첨부파일이 있고, 본문 내용중에 첨부된 형태로 하려면 다음과 같이 하면 된다.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 발송 계정 정보
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_email_password'
# 수신자 이메일 주소
to_email = 'recipient@example.com'
# 이메일 제목과 내용
subject = '이메일 제목'
body_html = """
<html>
<body>
<p>이메일 본문에 삽입된 이미지입니다.</p>
<img src="cid:image.jpg" alt="이미지">
</body>
</html>
"""
# MIMEText를 사용하여 이메일 메시지 설정
message = MIMEMultipart()
message['From'] = smtp_username
message['To'] = to_email
message['Subject'] = subject
message.attach(MIMEText(body_html, 'html'))
# 이미지 파일 첨부 및 본문에 삽입
image_path = 'path/to/your/image.jpg'
with open(image_path, 'rb') as img_file:
img_data = img_file.read()
image = MIMEImage(img_data, name='image.jpg')
image.add_header('Content-ID', '<image.jpg>')
message.attach(image)
# SMTP 서버에 연결
with smtplib.SMTP(smtp_server, smtp_port) as server:
# 연결 보안 설정 (TLS 사용)
server.starttls()
# 로그인
server.login(smtp_username, smtp_password)
# 이메일 발송
server.sendmail(smtp_username, to_email, message.as_string())
print('이메일이 발송되었습니다.')
이미지가 자체서버 안에 있는 경우가 아니라 외부에 있는 경우는 다음과 같이 작성할 수 있겠다.
import requests
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 발송 계정 정보
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_email@example.com'
smtp_password = 'your_email_password'
# 수신자 이메일 주소
to_email = 'recipient@example.com'
# 이메일 제목과 내용
subject = '이메일 제목'
body_html = """
<html>
<body>
<p>이메일 본문에 삽입된 이미지입니다.</p>
<img src="cid:image.jpg" alt="이미지">
</body>
</html>
"""
# MIMEText를 사용하여 이메일 메시지 설정
message = MIMEMultipart()
message['From'] = smtp_username
message['To'] = to_email
message['Subject'] = subject
message.attach(MIMEText(body_html, 'html'))
# 외부 서버에서 이미지 가져오기
image_url = 'https://example.com/path/to/your/image.jpg'
response = requests.get(image_url)
img_data = response.content
# 이미지 파일 첨부 및 본문에 삽입
image = MIMEImage(img_data, name='image.jpg')
image.add_header('Content-ID', '<image.jpg>')
message.attach(image)
# SMTP 서버에 연결
with smtplib.SMTP(smtp_server, smtp_port) as server:
# 연결 보안 설정 (TLS 사용)
server.starttls()
# 로그인
server.login(smtp_username, smtp_password)
# 이메일 발송
server.sendmail(smtp_username, to_email, message.as_string())
print('이메일이 발송되었습니다.')
'Python + Django' 카테고리의 다른 글
파이썬 웹크롤링 브라우저별 속도 테스트 Edge vs Chrome vs Firefox (0) | 2020.04.04 |
---|---|
어쩌다 파이썬 + 장고 (Python + Django) 2편 - django-instagram 프로젝트 따라해보기 (0) | 2020.03.31 |
어쩌다 파이썬 + 장고 (Python + Django) 1편 - 윈도우10에 파이썬 장고 설치 (0) | 2020.03.30 |