이메일을 보내는 파이썬 라이브러리
파이썬에서 이메일을 보내는 방법
- smtplib: 메일 전송 라이브러리
- email.mime: MIME 포맷(제목, 수신자, 본문, 첨부파일) 생성 라이브러리
위 두 가지 라이브러리가 필요하다. 특히 SMTP를 메인 프로토콜로 사용하게 되는데, 계정 비밀번호를 직접 넣으면 차단되니 반드시 App Password를 생성해서 사용해야 한다.
MIME(Multipurpose Internet Mail Extensions)은 이메일이나 웹 전송 시 텍스트 외에 이미지, 오디오, 첨부 파일 등 다양한 데이터 형식을 구조화하고 인코딩하는 표준 방식이다.
메일 구조 설계
파이썬에서 메일 구조를 어떻게 설계하느냐에 따라 다른 라이브러리를 사용해야 한다.
- 텍스트만 보내는 경우 → MIMEText
- 이미지나 파일을 보내는 경우 → MIMEBase
- 텍스트와 함께 이미지, 파일을 보내는 경우 → MIMEMultipart
대부분 텍스트와 함께 파일도 같이 보내기 때문에 MIMEMultipart를 이용해 생성하고 attach 함수를 이용해 메일을 만든다.
웹 크롤링 후 메일 보내기
from dotenv import load_dotenv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP
import os
import html_parser_me
load_dotenv()
def send_boan_news(news_list):
user_email = os.getenv("EMAIL_USER")
user_password = os.getenv("EMAIL_PASS")
smtp_sever = os.getenv("SMTP_SVR")
smtp_port = int(os.getenv("SMTP_PORT"))
# 메일 메시지 설계
msg = MIMEMultipart()
msg['Subject'] = "[최신 뉴스 전달] 실시간 보안 뉴스"
msg['From'] = user_email # 보내는 사람
msg['To'] = user_email # 받는 사람
html_content = f"""
<div style="font-family: 'Pretendard', 'Apple SD Gothic Neo', sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e1e4e8; border-radius: 12px; overflow: hidden; line-height: 1.6; background-color: #f8f9fa;">
<div style="background-color: #1a237e; padding: 30px 20px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 24px; letter-spacing: -0.5px;">🛡️ Weekly 보안 뉴스 브리핑</h1>
<p style="color: #c5cae9; margin: 10px 0 0 0; font-size: 14px;">보안 공부하는 학생들을 위한 최신 동향 리포트</p>
</div>
<div style="padding: 20px;">
<ul style="list-style: none; padding: 0; margin: 0;">
{''.join([f'''
<li style="background: #ffffff; margin-bottom: 15px; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-left: 4px solid #1a237e;">
<a href="{news['href']}" target="_blank" style="text-decoration: none; display: block;">
<div style="font-weight: 700; color: #222; font-size: 17px; margin-bottom: 12px; line-height: 1.4;">
{news['title']}
</div>
</a>
<div style="text-align: right; font-size: 13px;">
<span style="background: #e8eaf6; color: #1a237e; padding: 4px 10px; border-radius: 4px; font-weight: 600;">
✍️ {news['writer'][:7]}
</span>
<a href="{news['href']}" target="_blank" style="margin-left: 10px; color: #1a237e; text-decoration: underline; font-weight: bold;">
원문 보기
</a>
</div>
</li>
''' for news in news_list])}
</ul>
</div>
<div style="padding: 25px; background-color: #ffffff; text-align: center; border-top: 1px solid #eee;">
<p style="font-size: 12px; color: #999; margin: 0; line-height: 1.5;">
본 메일은 보안 학습을 위해 자동으로 수집된 정보입니다.<br>
<strong>제작자: 보안 꿈나무 개발자</strong>
</p>
</div>
</div>
"""
msg.attach(MIMEText(html_content, 'html'))
try:
with SMTP(smtp_sever, smtp_port) as server:
server.starttls()
server.login(user_email, user_password)
server.send_message(msg)
print("메일 발송 성공!")
except Exception as e:
print(f"오류 발생 : {e}")
if __name__ == "__main__":
news_list = html_parser_me.get_news()
send_boan_news(news_list[:10])
html_parser로 데이터를 추출하고 파싱한 다음, 이를 이메일화 해서 개인 이메일로 보내는 실습을 했다.
파일 보내기, 이미지 보내기

파일을 첨부하기 때문에 MIMEBase를 사용해 파일을 첨부했다. base64는 인코딩이고 파일이기 때문에 데이터가 많아 여러 개의 패킷을 보낼 것을 대비해 attachment 헤더가 들어간다.

'Security > SK Shieldus Rookies' 카테고리의 다른 글
| [SK 쉴더스 루키즈] openpyxl & schedule (0) | 2026.05.10 |
|---|---|
| [SK 쉴더스 루키즈] BeautifulSoup (0) | 2026.05.10 |
| [SK 쉴더스 루키즈] Notion API 연동 실습 (0) | 2026.05.06 |
| [SK 쉴더스 루키즈] Python 문법 1 (0) | 2026.04.29 |
| [SK 쉴더스 루키즈] Git & Github (0) | 2026.04.28 |
