1. 소개
Python으로 이메일을 보내는 것은 개인 애플리케이션과 비즈니스 시스템 모두에 매우 유용한 기술입니다. 예를 들어, 애플리케이션에서 사용자에게 자동으로 알림을 보내거나 시스템 오류 로그를 실시간으로 관리자에게 전달하는 데 사용할 수 있습니다. 또한, 수동으로가 아니라 코드를 통해 메일을 보내면 이메일 전송을 효율적으로 처리하고 일상 업무를 크게 간소화할 수 있습니다.
Python은 표준 라이브러리에 “smtplib”을 포함하고 있어 외부 모듈을 추가하지 않고도 기본적인 이메일 전송이 가능합니다.
이 글에서는 Python으로 이메일을 보내기 위한 기본 설정과 단계들을 설명하고 실제 코드 예제를 활용한 실용적인 방법을 소개합니다. 또한 HTML 형식 이메일, 첨부 파일이 있는 이메일 전송, Gmail 보안 설정, 일본어 이메일 전송, 다수 수신자에게 대량 전송 등 고급 주제도 자세히 다룹니다.
이 가이드를 끝까지 읽으면 Python으로 이메일을 손쉽게 보낼 수 있게 되며, 다양한 상황에 적용할 수 있는 지식을 갖추게 됩니다.
2. Python으로 이메일 보내기
Python으로 이메일을 보내려면 표준 라이브러리인 “smtplib”을 사용합니다. 이 라이브러리를 사용하면 코드를 작성하는 것만으로 SMTP 서버를 통해 이메일을 보낼 수 있습니다. 아래에서는 smtplib 모듈에 대한 자세한 개요와 이메일 전송을 위한 기본 단계들을 제공합니다.
smtplib 모듈 소개
smtplib 모듈은 Python 표준 라이브러리의 일부이며 SMTP 클라이언트 프로토콜을 지원합니다. 이 모듈을 사용하면 Python에서 직접 SMTP 서버에 연결하고 이메일을 보낼 수 있습니다.
smtplib의 주요 기능
- SMTP 서버와 쉽게 통신합니다.
- 별도의 외부 모듈이 필요 없으며 Python에 포함되어 있어 추가 설정이 필요 없습니다.
- 보안 설정 및 오류 처리를 지원합니다.
이메일 전송 기본 단계
이제 Python으로 이메일을 보내는 기본 단계를 살펴보겠습니다. 아래 단계들을 따라 하면 쉽게 이메일을 보낼 수 있습니다.
1. SMTP 서버에 연결하는 방법
먼저 SMTP 서버에 연결해야 합니다. 이는 이메일 전송의 시작점입니다. 일반적으로 Gmail, Yahoo Mail, Outlook 등 서비스에서 제공하는 SMTP 서버를 많이 사용하지만, 회사 전용 SMTP 서버를 사용할 수도 있습니다.
import smtplib
# SMTP server settings
smtp_server = "smtp.example.com" # Example: For Gmail, use "smtp.gmail.com"
smtp_port = 587 # Common port number. For Gmail, use 587
2. 로그인 인증 설정
SMTP 서버에 연결한 후, 발신자의 이메일 주소와 비밀번호로 로그인합니다. Gmail과 같은 서비스를 사용할 경우 추가 보안 설정이 필요할 수 있습니다.
# Email account information
username = "your_email@example.com"
password = "your_password"
# Connect and log in to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Establish a secure connection
server.login(username, password)
3. 이메일 생성 및 전송
다음으로 보낼 이메일의 내용을 작성합니다. 수신자 주소, 제목, 본문을 지정하고 SMTP 서버를 통해 전송합니다.
# Email sending information
to_address = "recipient@example.com"
subject = "Test email"
body = "This email was sent from Python."
# Email format
message = f"Subject: {subject}
{body}"
# Send email
server.sendmail(username, to_address, message)
print("Email has been sent!")
4. 오류 처리 핵심 포인트
SMTP 서버 연결 및 이메일 전송 과정에서 예상치 못한 오류가 발생할 수 있습니다. 따라서 try‑except 블록을 사용하여 오류를 적절히 처리하도록 합니다.
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message)
print("The email was sent successfully!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit() # Close the connection
요약
이 문서는 Python으로 이메일을 보내는 기본 절차를 다룹니다. 이 흐름을 배우면 이메일을 자동화하고, 한 번에 여러 메시지를 보내며, 다양한 방식으로 적용할 수 있습니다. 다음 섹션에서는 실제 코드 예제를 사용하여 일반 텍스트 이메일, HTML 이메일, 그리고 첨부 파일이 있는 이메일 전송을 자세히 살펴보겠습니다.

3. 실전: Python을 이용한 이메일 전송 코드 예제
이제부터 Python을 사용하여 이메일을 보내는 실제 코드 예제를 제시합니다. 일반 텍스트 이메일, HTML 이메일, 그리고 첨부 파일이 있는 이메일을 단계별로 어떻게 보내는지 설명합니다.
일반 텍스트 이메일 보내기
먼저, 가장 기본적인 형태인 일반 텍스트 이메일을 보내는 방법을 소개합니다. 간단한 텍스트 메시지를 보내기 위해 smtplib 모듈을 사용할 것입니다.
코드 예제
import smtplib
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "Plain text email test"
body = "This is a plain text email sent from Python."
# Email format
message = f"Subject: {subject}
{body}"
try:
# Connect to the server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message)
print("Plain text email sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
HTML 이메일 보내기
다음으로, HTML 형식의 이메일을 보내는 방법을 설명합니다. HTML 이메일을 사용하면 본문을 스타일링하고 링크를 삽입할 수 있습니다. 이메일 본문에 HTML 코드를 포함할 때는 email.mime 모듈을 사용하여 HTML을 올바르게 처리합니다.
코드 예제
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "HTML email test"
html_content = '''
<html>
<body>
<h1>Hello</h1>
<p>This is an HTML-formatted email sent from <strong>Python</strong>.</p>
<a href="https://example.com">Click here</a>
</body>
</html>
'''
# Create the email
message = MIMEMultipart()
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
message.attach(MIMEText(html_content, "html"))
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("HTML email sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
첨부 파일이 있는 이메일 보내기
다음으로, 파일을 첨부한 이메일을 보내는 방법을 보여드립니다. 예를 들어 PDF나 이미지를 이메일에 첨부할 수 있습니다. 이는 email.mime 모듈의 MIMEBase 클래스를 사용합니다.
코드 예제
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "Test email with attachment"
body = "I have attached a file. Please check it."
# Create the email
message = MIMEMultipart()
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# Attach file
filename = "example.pdf" # Name of the file to attach
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={filename}")
message.attach(part)
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("Email with attachment sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
요약
위의 코드 예제를 사용하면 Python으로 다양한 유형의 이메일을 보낼 수 있습니다. 필요에 따라 일반 텍스트, HTML, 또는 첨부 파일이 포함된 이메일 중에서 선택할 수 있습니다. 다음 섹션에서는 Gmail을 예시로 들어 특정 SMTP 서버를 사용할 때의 설정 및 주의 사항을 설명합니다.
4. Gmail을 사용한 이메일 전송
이 섹션에서는 Python을 이용해 Gmail로 이메일을 보내는 방법을 자세히 설명합니다. Gmail은 널리 사용되며 Python 프로그램이 쉽게 접근할 수 있는 SMTP 서버를 제공합니다. 그러나 Gmail을 통해 메일을 보내려면 몇 가지 보안 설정이 필요합니다.
Gmail SMTP 설정
Gmail을 사용해 메일을 보내려면 다음 SMTP 서버 정보를 사용하십시오:
- SMTP 서버 :
smtp.gmail.com - 포트 : 587 (TLS 사용) 또는 465 (SSL 사용)
- 인증 : 필요
기본 설정 코드 예시
import smtplib
from email.mime.text import MIMEText
# Gmail SMTP server settings
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_password"
# Recipient and content
to_address = "recipient@example.com"
subject = "Test email from Gmail"
body = "This email was sent through Gmail from Python."
# Create the email content
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
# Connect to the server and send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Use TLS to enhance security
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("The email was sent using Gmail!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
보안 고려 사항
Gmail 계정을 사용할 때는 보안 설정을 검토해야 합니다. Gmail은 일반적으로 타사 애플리케이션의 접근에 보안 제한을 두고 있습니다. 따라서 Python에서 접근할 때는 다음 단계가 필요합니다.
앱 비밀번호 얻기
- 2단계 인증 활성화 : Gmail 계정 설정에서 2단계 인증을 켭니다. 이를 통해 앱 비밀번호를 생성할 수 있습니다.
- 앱 비밀번호 생성 : Gmail의 계정 설정 > 보안 > 앱 비밀번호에서 Python 프로그램 전용 앱 비밀번호를 생성합니다. 이 비밀번호는 일반 로그인 비밀번호 대신 사용됩니다.
참고 사항
- 앱 비밀번호 관리 : 앱 비밀번호는 철저히 비밀로 유지하고 안전하게 보관하십시오.
- 계정 보안 : 앱 비밀번호를 사용하면 Gmail 계정에 대한 무단 접근을 방지하는 데 도움이 됩니다.
코드 예시 (앱 비밀번호 사용)
앱 비밀번호를 사용할 때, 코드는 다음과 같습니다.
import smtplib
from email.mime.text import MIMEText
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
app_password = "your_app_password" # Use an app password instead of your regular password
to_address = "recipient@example.com"
subject = "Test email from Gmail using an app password"
body = "This email was sent from Gmail using an app password."
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, app_password)
server.sendmail(username, to_address, message.as_string())
print("The email was sent using Gmail!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
Summary
Python을 통해 Gmail로 이메일을 보낼 때, 계정 보안 설정이 중요합니다. 앱 비밀번호를 사용하면 이메일을 보다 안전하게 보낼 수 있습니다. 다음 섹션에서는 다수 수신자에게 보내기, 예약 자동 전송, 일본어 이메일 전송 등 Python의 고급 이메일 전송 기술을 소개합니다. 
5. 고급 응용: 이메일 전송 기술
이제부터 Python에서 고급 이메일 전송 기술을 다룹니다. 이 섹션에서는 다수 수신자에게 대량 전송, 예약 이메일 자동화, 일본어 이메일 전송과 같은 실용적인 방법을 설명합니다.
다수 수신자에게 보내기
Python을 사용하면 한 번에 여러 수신자에게 메시지를 보낼 수 있습니다. 이메일의 “To”, “Cc”, “Bcc” 필드를 올바르게 설정하고 수신자를 리스트로 관리하면 대량 전송이 간단해집니다.
코드 예시
아래는 “To” 필드에 여러 수신자를 지정하는 코드 예시입니다.
import smtplib
from email.mime.text import MIMEText
# SMTP server info
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
# Recipient list
to_addresses = ["recipient1@example.com", "recipient2@example.com"]
subject = "Test email to multiple recipients"
body = "This email was sent to multiple recipients at once."
# Create the email
message = MIMEText(body)
message["From"] = username
message["To"] = ", ".join(to_addresses) # Separate multiple recipients with commas
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_addresses, message.as_string())
print("The email to multiple recipients has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
예약 이메일 자동 전송
주기적으로 이메일을 보내려면 스케줄을 설정하는 것이 유용합니다. Python에는 시간 간격에 따라 반복 작업을 실행할 수 있는 “schedule” 라이브러리와 “time” 모듈이 있습니다. 예를 들어, 특정 시간에 자동으로 이메일을 보내는 스크립트를 구성할 수 있습니다.
코드 예시 (schedule을 사용한 예약 전송)
import smtplib
from email.mime.text import MIMEText
import schedule
import time
def send_email():
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
to_address = "recipient@example.com"
subject = "Scheduled email"
body = "This is an email sent on a regular schedule."
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("Email has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
# Send the email every day at 9:00 AM
schedule.every().day.at("09:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
이 스크립트는 지정된 시간(여기서는 오전 9시)에 매일 자동으로 이메일을 보냅니다.
일본어로 이메일 보내기
Python으로 일본어 이메일을 보낼 때는 인코딩에 주의해야 합니다. 특히 제목과 본문에 일본어가 포함된 경우, 올바른 전송을 위해 UTF-8 인코딩을 사용하도록 메시지를 설정하세요.
코드 예시 (일본어 지원)
import smtplib
from email.mime.text import MIMEText
from email.header import Header
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
to_address = "recipient@example.com"
# Japanese subject and body
subject = Header("Test email in Japanese", "utf-8")
body = "This is an email sent in Japanese from Python."
message = MIMEText(body, "plain", "utf-8")
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("The Japanese email has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
요약
이 섹션에서는 Python에서 고급 이메일 전송 기술을 다루었습니다. 다중 수신자에게 보내기, 예약된 이메일 자동화, 일본어 지원과 같은 기능을 활용하면 이메일 전송이 더욱 실용적입니다. 다음 섹션에서는 기사 전체를 요약하고 핵심 포인트를 정리합니다.
6. 요약
이 문서는 Python을 사용해 이메일을 보내는 방법을 기본부터 고급 기술까지 단계별로 설명했습니다. Python 표준 라이브러리인 smtplib을 활용하면 이메일 전송이 간단해지며 일상 업무와 애플리케이션에 적용할 수 있습니다. 아래는 각 섹션에서 배운 핵심 포인트를 정리한 내용입니다.
- 이메일 전송 기본 단계
- Python의 smtplib 모듈을 사용해 SMTP 서버를 통해 이메일을 보내는 방법을 배웠습니다.
- 이메일 작성부터 전송까지의 흐름과 오류 처리의 중요성을 다루었습니다.
- 실용적인 이메일 전송 코드 예시
- 일반 텍스트 이메일, HTML 이메일, 첨부 파일이 포함된 이메일을 보내는 코드를 소개했습니다.
- 이를 통해 다양한 이메일 형식에 맞게 코드를 적용할 수 있습니다.
- Gmail을 이용한 이메일 전송
- Gmail의 SMTP 서버 설정과 앱 비밀번호를 이용한 보안 조치를 설명했습니다.
- Gmail 계정을 사용할 때는 2단계 인증을 활성화하고 앱 비밀번호를 설정해야 함을 강조했습니다.
- 고급 이메일 전송 기술
- 다중 수신자에게 보내기, 예약된 이메일 자동화, 일본어 콘텐츠 처리 기술을 다루었습니다.
- 특히 제목이나 본문에 일본어가 포함된 경우 올바른 인코딩 설정이 중요함을 강조했습니다.
이 가이드 활용 방법
이 가이드를 따라 하면 Python을 사용하여 자동 이메일 발송기, 예약 알림 시스템 또는 알림 애플리케이션을 구축할 수 있습니다. 실용적인 기술로서 고객 지원, 운영 관리 또는 알림 서비스의 일부로 적용할 수 있습니다.
Python으로 이메일을 보내는 것은 다양한 작업과 사용 사례에 적용할 수 있으며, 그 편리함과 유연성은 비즈니스에 큰 도움이 될 수 있습니다. 한번 시도해 보고 프로젝트에 통합해 보세요.



