Python

Python으로 Gmail계정으로 메일전송하기

지오준 2021. 2. 26.
반응형

1.Gmail계정에서 2단계인증 설정

2.앱 비밀번호 설정

3. Python 샘플코드

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import ssl
import datetime 
from os.path import basename

gmail_account_id = "xxx@gmail.com"         #Gmail계정ID
gmail_account_pass = "xxxxxxxxxxxxxxxx"    #Gmail계정의앱비밀번호16자리

# Message의Email전송함수
def sendMessage(to_email, from_email, subject, message):
    try:
        print("【MessageEmail송신시작】:" + str(datetime.datetime.now()))
        
        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["To"] = to_email
        msg["From"] = from_email
        msg.attach(MIMEText(message))

        # 메일송신처리
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(gmail_account_id, gmail_account_pass)
        server.send_message(msg)
        server.quit()

    except Exception as e:
        errordate = str(datetime.datetime.now())

        print("【=== 에러내용 ===】:" + errordate)
        print("type:" + str(type(e)))
        print("args:" + str(e.args))
        print("e自身:" + str(e))

    else:
        print("【정상적으로 Message의Email송신이 완료됬습니다.】:" + str(datetime.datetime.now()))
    finally:
        print("【Message의Email송신완료】:" + str(datetime.datetime.now()))

# Message와File의Email송신함수
def sendMultiMessage(to_email, from_email, subject, message, filepath):
    try:
        print("【Message와File의Email송신시작】:" + str(datetime.datetime.now()))
        
        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["To"] = to_email
        msg["From"] = from_email
        msg.attach(MIMEText(message))

        # 파일첨부
        with open(filepath, "rb") as f:
            part = MIMEApplication(
                f.read(),
                Name=basename(filepath)
            )
        
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(filepath)
        msg.attach(part)

        # 메일송신처리
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(gmail_account_id, gmail_account_pass)
        server.send_message(msg)
        server.quit()

    except Exception as e:
        errordate = str(datetime.datetime.now())

        print("【=== 에러내용 ===】:" + errordate)
        print("type:" + str(type(e)))
        print("args:" + str(e.args))
        print("e자신:" + str(e))

    else:
        print("【정상적으로 Message와File의Email송신이 완료됬습니다.】:" + str(datetime.datetime.now()))
    finally:
        print("【Message와File의Email송신완료】:" + str(datetime.datetime.now()))
반응형

댓글