[ Python ] Gmail로 메일 보내기

2019. 10. 26. 17:04분석 Python/구현 및 자료

728x90

먼가 돌아가는 것에 대해서 error 같은 것을 빨리 체크하기 위해서 logging 작업을 하긴 하지만, 

다른 작업과 병행을 하다보면 확인하기가 어려울 때가 있어서, 시간을 낭비할 우려가 있다.

그래서 이런 문제를 해결 하기 위해 에러가 날 때 메일을 보내주면, 더 쉽게 파악할 수 있지 않을까 생각을 했다.

그래서 오늘에서야 자료를 찾고 시도해봤다!

역시 파이썬에서는 이미 구현이 되어 있어서 참 편하게 아래 방법을 잘 따라 하니 바로 되었다!

일단은 구글 메일로 보내는 것을 할 예정이고, 구글 아이디에서 해줘야하는 것이 있다.

네이버도 된다고 하니, 아래 medium url을 눌러서 해보시면 된다!

구글 계정 로그인 -> 보안 -> 보안 수준이 낮은 앱으로 엑세스를 사용 

나의 보안을 주고 편리함을 얻자 (뼈를 주고 살을 취하는 그런 느낌?....)

보안을 주고 편함을 얻기

저렇게 접근을 허용시키고 아래 코드를 활용하면 된다!

추가) 해당하는 노트북 이름을 가지고 와서 메일 제목에 추가로 알려줄 수 있게 설정함. 

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
## 주의 다른 cell에서 해야함

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${window.document.getElementById("notebook_name").innerHTML}'`);
print(notebookName)

이제 메일로 전송시켜보자!

message ="""Subject: "{notebook}" 에러 발생 문자
To: {recipient}
From: {sender}

Hi {name}, 안타깝게도 다음과 같은 에러가 발생했습니다 

Error : {error}

코드를 수정하세요.
"""


sender_email = '####@gmail.com' #'‘sendermail@example.com’       # 송신 메일
receiver_email = '####@gmail.com'        # 수신 메일
login = '####@gmail.com'
password = '#####'
with smtplib.SMTP_SSL("smtp.gmail.com") as server:
    server.login(login, password)
    server.sendmail(sender_email,
                    receiver_email,
                    message.format(name = "SR", sender = sender_email , 
                                   recipient= receiver_email ,
                                   error = "ValueError" , 
                                   notebook = notebookName , 
                                  ).encode("utf-8")
                    )
print('Sent') 

- 성공 - 

plotly 결과물도 이메일로 보낼 수 있다.

https://plot.ly/python/email-reports/

 

Emailing Plotly Graphs with Python

How to email Plotly graphs in HTML reports with Python.

plot.ly

 

https://blog.mailtrap.io/sending-emails-in-python-tutorial-with-code-examples/

 

Sending Emails in Python - Tutorial with Code Examples | Mailtrap Blog

Images, attachments, personalization, multiple recipients, HTML emails and sending via Gmail in one guide.

blog.mailtrap.io

 

https://medium.com/sjk5766/python-gmail-naver-%EB%A9%94%EC%9D%BC-%EC%A0%84%EC%86%A1-4014fa ef25c4

 

Python Gmail, naver 메일 전송

언젠가 필요할 날이 있을 것 같아 메일전송이 성공한 base 코드를 기록해 둔다. Python 버전 3에서 테스트 하였으며, 메일을 받는 쪽(GMail, Naver)에서는 메일을 받을 수 있도록 설정을 따로 해야한다.

medium.com

 

728x90