반응형
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()))
반응형
'Python' 카테고리의 다른 글
Python으로 Gmail발송시 에러(smtplib.SMTPAuthenticationError: (535, ‘5.7.8 Username and Password not accepted. Learn more at\n5.7.8)) 해결방법 (3) | 2021.08.15 |
---|---|
Visual Source Code에서 Python 작성 모듈참조시 에러 발생시 해결방법(unsolved import '참조디렉토리명') (0) | 2021.05.23 |
Python의 Flask를 이용한 apscheduler소스 코드 (0) | 2021.03.11 |
Oracle Cloud Object Storage관련 Python소스 코드 (0) | 2021.03.03 |
Python 크롤링 샘플 (0) | 2021.02.28 |
댓글