yhansol
hansol
yhansol
전체 방문자
오늘
어제
  • 분류 전체보기 (26)
    • 😎 (1)
    • database (5)
    • mobile (1)
    • node.js (7)
    • javascript (3)
    • java (4)
    • 자료구조 (1)
    • 관련서적 (0)
    • git & github (0)
    • http (2)
    • python (1)
    • aws (1)

블로그 메뉴

  • 방명록
  • 🐱github
  • 💡notion
  • 📷instagram

공지사항

인기 글

태그

  • JRebel
  • MongoDB
  • 생활코딩
  • NoSQL
  • Asynchronous
  • Node
  • Chrome
  • blocking
  • github
  • 계층형쿼리
  • velog
  • TypeScript
  • V8
  • redis
  • node.js
  • Non blocking
  • Synchronous
  • NPM
  • Database
  • decoding
  • RESTful
  • stack
  • SQL
  • pm2
  • JavaScript
  • BASE64
  • graphQL
  • intellij
  • bun
  • obejct

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
yhansol

hansol

python

[python] smtp 메일 보내기

2023. 10. 14. 12:40
728x90
반응형

파이썬 'smtplib' 를 통해 메일을 보낼 수 있다.

cron을 통해 특정주기마다 반복적으로 메일을 보내는 방법을 소개한다.

 

import smtplib
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

html_content = """
<html>
<head></head>
<body>
	<p>
    	파이썬 코드로 메일 보내기
    </p>
</body>
</html>
"""

def send_mail(addr):
    reg = "^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$"  # 유효성 검사
    if re.match(reg, addr):
        smtp.sendmail(my_account, to_mail, msg.as_string())
        print("정상적으로 메일이 발송되었습니다.")
    else:
        print("받으실 메일 주소를 정확히 입력하십시오.")

# smpt 연결
gmail_smtp = "smtp.gmail.com"
gmail_port = 465
smtp = smtplib.SMTP_SSL(gmail_smtp, gmail_port)

# login
my_account = "보낼메일 주소"
my_password = "패스워드"
smtp.login(my_account, my_password)

# to
to_mail = "받을메일 주소"

# info
msg = MIMEMultipart()
msg["Subject"] = "메일 제목"
msg["From"] = my_account
msg["To"] = to_mail

# content
content_part = MIMEText(html_content, "html")
msg.attach(content_part)

# attach
file = "파일경로" # 절대경로 혹은 상대경로
with open(file, 'rb') as attachment:
        part = MIMEApplication(attachment.read(), Name = "첨부파일 이름")
        part['Content-Disposition'] = 'attachment; filename = "첨부파일 이름"
        msg.attach(part)

send_mail(to_mail)

smtp.quit()

위 코드는 간단하게 메일을 보낼 수 있는 예시이다.

첨부파일을 사용하기 위해 'from eamil.mime.application import MIMEApplication' 을 임포트 하고 작성한다.

 

로그인에 필요한 메일 패스워드는 기존에 우리가 알던 로그인할때 필요한 패스워드가 아닌 앱 비밀번호로 구글 설정에 들어가서 확인해야한다.

https://myaccount.google.com/security 링크 접속 > 2단계인증 > 하단에 앱 비밀번호 설정 > 앱 비밀번호 생성 > 생성된 키 사용

 

 

    yhansol
    yhansol

    티스토리툴바