backend/python

sending gmail by python3

seul chan 2016. 11. 23. 15:49

sending email by Python


# 이메일을 보내기 위한 smtplib 모듈을 import 한다

import smtplib


# 그 이후에는 일단 복붙으로 구현

--------------------------------------------------------

# -*- coding:utf-8 -*-


import smtplib


TO = "bartkim0426@gmail.com,"

SUBJECT = 'Testing email'

TEXT = """

testing - \n

sending email in python \n

by seul, loving in suwon

""" # plain text  


# Gmail Sign In  

gmail_sender = 'bartkim0426@gmail.com'  

gmail_passwd = 'tmfcks47'  


server = smtplib.SMTP('smtp.gmail.com', 587)  

server.ehlo()  

server.starttls()  

server.login(gmail_sender, gmail_passwd)  


BODY = '\r\n'.join(['To: %s' % TO,  

                    'From: %s' % gmail_sender,  

                    'Subject: %s' % SUBJECT,  

                    '', TEXT])  


try:  

    server.sendmail(gmail_sender, [TO], BODY)  

    print ('email sent')  

except:  

    print ('error sending mail')  


server.quit()  

-----------------------------------


#text 파일을 gmail로 sending하는 def

-----------------------------------------


# txt 파일을 읽어서 gmail로 보내기


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

receiver = ["bartkim0426@gmail.com",]

Ccuser = ["bartkim0426@gmail.com"]

mail_title = "테스트 메일"


ToUser = receiver

# CcUser = ['참조할 사람 메일 주소1', '참조할 사람 메일 주소2']

 

FromUser = 'bartkim0426@gmail.com'

Passwd = 'tmfcks47'

Server= 'smtp.gmail.com'

Port = 587

 

Subject = "{mail_title}".format(mail_title = mail_title)

 

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("./crawling/albamon.txt", '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)

-----------------------------------------------------------------


참고 url

http://carpedm20.blogspot.kr/2013/04/python-email.htmlhttp://blog.saltfactory.net/python/send-mail-via-smtp-and-python.html

http://grephappy.tistory.com/19 (정 안되면 복붙)

https://gist.github.com/iz4blue/2effb931fdc584a2c641

'backend > python' 카테고리의 다른 글

selenium: webelement 명령어  (0) 2016.12.15
vim 명령어  (0) 2016.12.03
파이썬 날짜, 시간 관련 모듈  (0) 2016.11.19
파이썬에서 파일 입출력하기  (0) 2016.11.19
iterator, generator  (0) 2016.11.19