단체 메일을 보낼 때, 사람에 따라 다른 내용과 파일 첨부를 해야할 경우가 많다.
GOOGLE GMAIL로 여러명에게 단체 메일 보내는 코드를 매월 유용하게 사용하고 있어 소개한다. :)
1. 구글메일 설정 방법
2. 본문 내용과 제목에 개인별로 다른 내용이 들어가야 할 경우 (제목 및 본문 내용 변경)
3. 개인별로 다른 이름의 첨부파일 첨부하기
4. 전체 Code는 하단에!
1. 구글메일 설정 방법
① IMAP 사용 설정 |
Gmail 내 톱니바퀴 모양(설정)을 클릭한다!
설정 상단 탭 중 '전달 및 POP/IMAP' 설정 클릭
IMAP 사용 체크 & 저장 까지 해주면 완료!
② 보안설정 |
하단 링크 접속 및 보안설정
2단계 인증사용함으로 변경
앱 비밀번호 클릭 & 생성
※이때 생성된 16글자 비밀번호는 따로 저장해야한다!
비밀번호는 구글 계정에 완전한 접근이 가능하므로 공유하지 않는 것을 권장하고 있다 :)
2. 본문 내용과 제목에 개인별로 다른 내용이 들어가야 할 경우
① 이메일 수신인 정보 Setting (엑셀파일)
rep |
krep |
num |
team |
part |
|
이름(영문) |
이름(한글) |
사번 |
팀명 |
파트명 |
이메일 |
Gildong Hong |
홍길동 |
A2Gei013 |
팀 |
A |
Gildong.Hong@naver.com |
위 Header를 기준으로 코드에 입력한다 (rep, krep, num, team, part, email)
< 코드 설명 >
> 앞서 저장한 이메일 수신정보 Setting 파일 불러오기
## 이메일 수신정보 Setting 파일 import
file = pd.read_excel(r'파일위치\파일이름.형식')
> for문에서 header를 불러온 후, 필요한 위치에 넣어주기
메일 제목에 개인별 이름을 다르게 넣고 싶다면 아래 코드처럼 %s를 써준 후 %헤더명(%krep) 을 사용하면 된다.
'메일제목_%s' % krep
> 본문 코드
영문이름, 국문이름, 사번, 팀명, 파트명은 각각 %s를 넣어준 후
하단에 한번에 % (rep, krep, num, team, part)를 써 주었다.
구글 메일을 보낼 때, 받는이 / 참조 / 숨은참조 를 각각 설정할 수 있다.
받는이를 비밀로 하여 숨기고 싶을 때는 Bcc를 사용하면 된다.
for rep, krep, num, team, part, email in zip(file.rep, file.krep, file.num, file.team, file.part, file.email):
# 수신인, 제목, 본문 작성
msg = MIMEMultipart()
msg['From'] = "aaa@naver.com" ### 발신인 email 주소
msg['To'] = "%s" % email ### 수신인 email 주소
msg['Cc'] = "bbb@naver.com, ccc@naver.com" ### 참조인 email 주소 (여러명일 경우 컴마','로 연결)
msg['Bcc'] = "ddd@naver.com" ### 숨은참조 email 주소
msg['Subject'] = '메일제목_%s' % krep
msg.attach(MIMEText('''
본문 내용 작성
영문이름 : %s
국문이름 : %s
사번 : %s
팀명 : %s
파트명 : %s
본문 내용 작성
''' % (rep, krep, num, team, part), 'plain'))
3. 개인별로 다른 이름의 첨부파일 첨부하기
첨부파일 이름에 이메일 수신인 정보 EXCEL 파일에서 설정한 개인별 이름 (krep)을 각각 넣어보자.
- 위에서 봤던 것처럼 filename과 attachment에 %s를 써준 후 %헤더명(%krep) 을 사용하면 된다!
# 파일첨부 (파일 미첨부시 생략가능)
filename = '첨부파일이름_%s.xlsx' % krep
attachment = open(r'파일위치\첨부파일이름_%s.xlsx' % krep, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment", filename= os.path.basename(filename))
msg.attach(part)
filename 은 메일에 표시될 첨부파일 이름
attachment 는 내가 첨부할 파일 위치와 이름 이다.
즉, filename과 attachment에 있는 첨부파일 이름이 같아도 되지만,
내가 가지고있는 파일명과 보내는 파일명을 다르게 설정할 수 있다.
(ex) 원하는 첨부파일명 : 21년 04월 실적_홍길동 / 내 파일명 21년 실적_ 홍길동
filename = '21년 04월 실적_%s.xlsx' % krep
attachment = open(r'파일위치\21년 실적_%s.xlsx' % krep, 'rb')
4. 전체 Code
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import pandas as pd
import os
## 세션생성, 로그인
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(이메일, 16자리비밀번호) ### Setting된 이메일 / 16자리 비밀번호
## 이메일 수신정보 Setting 파일 import
file = pd.read_excel(r'파일위치\파일이름.형식')
#불러오는 파일의 header가 rep / krep / num / team / part / email 이 있어야함 ↑↑↑↑↑ ↓↓↓↓↓
for rep, krep, num, team, part, email in zip(file.rep, file.krep, file.num, file.team, file.part, file.email):
# 수신인, 제목, 본문 작성
msg = MIMEMultipart()
msg['From'] = "aaa@naver.com" ### 발신인 email 주소
msg['To'] = "%s" % email ### 수신인 email 주소
msg['Cc'] = "bbb@naver.com, ccc@naver.com" ### 참조인 email 주소 (여러명일 경우 컴마','로 연결)
msg['Bcc'] = "ddd@naver.com" ### 숨은참조 email 주소
msg['Subject'] = '메일제목_%s' % krep
msg.attach(MIMEText('''
본문 내용 작성
영문이름 : %s
국문이름 : %s
사번 : %s
팀명 : %s
파트명 : %s
본문 내용 작성
''' % (rep, krep, num, team, part), 'plain'))
# 파일첨부 (파일 미첨부시 생략가능)
filename = '첨부파일이름_%s.xlsx' % krep
attachment = open(r'파일위치\첨부파일이름_%s.xlsx' % krep, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment", filename= os.path.basename(filename))
msg.attach(part)
# 메일 전송
# MAIL(발신자) 설정
sender = msg['From'];
# RCPT(수신자), 리스트로 보낸다.
# 수신자 추가
receiver = msg['To'].split(",");
# 참조자 추가
if msg['Cc'] is not None:
receiver += msg['Cc'].split(",");
s.sendmail(sender, receiver, msg.as_string())
s.quit()
※ 참고사이트
업무에서는 주로 개인별로 정보가 담긴 파일을 먼저 생성한 후,
구글에서 첨부파일을 포함해서
각 사람들에게 개인별로 메일을 전송하고 있다.
개인별 파일 분할 생성 (여러시트 가능) https://blog.naver.com/2526389/222319517865
댓글