Python email 보내기 (google smtp server 사용) source 입니다.
class를 사용하긴 했지만,
아래 프로그램을 실행하기 전에 google e-mail계정이 필요하고 smtp 에 접근할 수 있도록 보안 수준낮은앱 허용을 해 주어야 합니다. ( 이거 안해주면, e-mail 계정에 접근할 수가 없습니다.)
gmail 계정: yourMail@gmail.com
smtp server: yourMail@gmail.com
smtp server password : yourMail@gmail.com 의 Password
파일명 : email.py 만 아니면 됨. ( email.py 로 사용하면 절대 안됨)
toMail : 받는사람 이메일( 여기서는 test 목적으로 자신에게 메일을 씀.)
attachedfile: sourcePath/log/attachedfile.txt 라고 놓으면 됨. ( 위치는 알아서 바꿔보길.)
----------------------------------------------------------------------------------------------------------------
# -*- coding:utf-8 -*-
'''
Created on 2018. 6. 14.
@author:
'''
import smtplib
import os
import email
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
class cEMail():
# eMail Provide SMTP ServerName Port 추가 설정
# Live smtp.live.com 587
# GMail smtp.gmail.com 587 개인 설정->계정 액세스 권한을 가진 앱 ->보안 수준이 낮은 앱 허용: 사용
def __init__(self,smtpServer, password='password'):
#print( "cEMail __init__")
self.smtpServer=smtpServer
self.smtp = smtplib.SMTP('smtp.gmail.com')
self.smtp.ehlo() # say Hello
self.smtp.starttls() # TLS 사용시 필요
self.smtp.login(self.smtpServer, password)
def __del__(self):
#print( "cEMail __del__")
try:self.smtp.quit()
except:pass
def send(self,toEMail,subject,message):
msg = MIMEText(message)
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg['From'] = self.smtpServer
msg['To'] = toEMail
fromEMail=self.smtpServer
self.smtp.sendmail(fromEMail, toEMail, msg.as_string())
def sendAttached(self,toEMail,subject,message,files=[]):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg['From'] = self.smtpServer
msg['To'] = toEMail
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
email.encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(os.path.basename(path)))
msg.attach(part)
fromEMail=self.smtpServer
self.smtp.sendmail(fromEMail, toEMail, msg.as_string())
print("Complete to send EMail to destination...")
if __name__ == '__main__':
smtp_server='yourMail@gmail.com'
smtp_server_password='password'
m_eMail =cEMail(smtp_server,smtp_server_password)
toMail='yourMail@gmail.com'
Subject='Test Mail'
Message='안녕하세요 \n이 메일은 파이썬에서 보내는 테스트 메일 입니다.\n감사합니다.'
m_eMail.send(toMail,Subject,Message)
toMail='yourMail@gmail.com'
Subject='Test Mail with files attached'
Message='안녕하세요 \n이 메일은 파이썬에서 보내는 첨부 파일 이 있는 테스트 메일 입니다.\n감사합니다.'
m_eMail.sendAttached(toMail,Subject,Message,['log/attachedfile.txt'])
'언어 > Python' 카테고리의 다른 글
Python qt5 Dialog modal modalness 적용 방법 (1) | 2019.08.16 |
---|---|
국제 금/은/구리 및 텍사스/두바이 중질유 석유값 가져 오기 (0) | 2019.08.16 |
QT5 push button color checkbox color combobox color (0) | 2018.03.07 |
[Python] URL link 파일 다운로드 (0) | 2018.02.20 |
리눅스 우분투 자바 인스톨 (0) | 2017.12.07 |