본문 바로가기

Python_Intermediate/Automation

Gmail Python Send(Add File)

반응형

1. 선수 작업

- 구글 로그인

- 구글 2차 비밀번호 생성

- 구글 앱 비밀번호 생성(기타 -> Python)


2. 코드

import os.path
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

content_type = "html"
username = '구글메일주소'
password = '구글보안비밀번호'
smtp = 'smtp.gmail.com'
port = 587
from_addr = "보내는 사람 주소"
to_addr = "받는 사람 주소"
subject = '메일제목'

files = ["첨부파일경로"]

content = """<html>
<head></head>
<body>
</body>
</html>"""

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr

msg.attach(MIMEText(content, content_type))

if files:
for f in files:
with open(f, 'rb') as a_file:
basename = os.path.basename(f)
part = MIMEApplication(a_file.read(), Name=basename)


part['Content-Disposition'] = 'attachment; filename="%s"' % basename
msg.attach(part)

mail = SMTP(smtp)
mail.ehlo()
mail.starttls()
mail.login(username, password)
mail.sendmail(from_addr, to_addr, msg.as_string())
mail.quit()


3. Html 코드를 사용하여 메일 본문 내용을 작성하고 첨부파일과 함께 보내는 구조

4. ImportError: DLL load failed: %1은(는) 올바른 Win32 응용 프로그램이 아닙니다. 오류 발생시 IDEL에서 직접 실행 또는 CMD에서 실행

반응형