smtp로 메일 보내기 샘플
contents.txt 파일의 내용을 읽어 메일 보내는 예제
1. https://docs.python.org/3.1/library/email-examples.html
2. http://blog.saltfactory.net/python/send-mail-via-smtp-and-python.html
3. http://stackoverflow.com/questions/19606778/sending-mail-error-with-python-smtplib
contents.txt 파일의 내용을 읽어 메일 보내는 예제
import smtplib from email.header import Header from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email import utils from email import encoders import os ToUser = ['받는 사람 메일 주소1', '받는 사람 메일 주소2'] CcUser = ['참조할 사람 메일 주소1', '참조할 사람 메일 주소2'] FromUser = '보내는 사람 메일 주소' Passwd = '비밀번호' Server= 'smtp.gmail.com' Port = 587 Subject = "메일 제목" def send_email(from_user, to_user, cc_users, subject, textfile, attach): COMMASPACE = ', ' msg = MIMEMultipart('alternative') msg['FROM'] = from_user msg['To'] = COMMASPACE.join(to_user) msg['Cc'] = COMMASPACE.join(cc_users) msg['Subject'] = Header(s=subject, charset='utf-8') msg['Date'] = utils.formatdate(localtime = 1) fp = open(textfile, 'rb') msg.attach(MIMEText(fp.read().decode('utf8', 'ignore'))) fp.close() if (attach != None): part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) encoders.encode_base64(part) filename = os.path.basename(attach) part.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(part) #print(Server + ":" + str(Port) + " connecting...") try: smtp = smtplib.SMTP(Server, Port) #smtp.set_debuglevel(1) try: #smtpserver.ehlo() smtp.starttls() smtp.login(FromUser, Passwd) smtp.sendmail(from_user, cc_users, msg.as_string()) print("[OK] send mail") except: print("[Error] Fail to send mail") finally: #smtp.close() smtp.quit() except: #debug('sendmail', traceback.format_exc().splitlines()[-1]) print("[Error] could no connect") return False send_email(FromUser, ToUser, CcUser, Subject, 'contents.txt', None)<참조>
1. https://docs.python.org/3.1/library/email-examples.html
2. http://blog.saltfactory.net/python/send-mail-via-smtp-and-python.html
3. http://stackoverflow.com/questions/19606778/sending-mail-error-with-python-smtplib