Exemple #1
0
 def send_mime(self, to_email: str, mime: MIMEBase):
     if self.smtp:
         self.smtp.sendmail(self.from_email, to_email, mime.as_string())
     if self.log:
         print('SENDING EMAIL')
         print('=' * 20)
         print(mime.as_string())
         print('=' * 20)
Exemple #2
0
    def _attach_blob(self, blob, **params):
        ref = params["document"]
        filename = os.path.basename(ref)

        container = MIMEMultipart("related", type="application/json+nxrequest", start="request")

        d = {"params": params}
        json_data = json.dumps(d, sort_keys=True)
        json_part = MIMEBase("application", "json+nxrequest")
        json_part.add_header("Content-ID", "request")
        json_part.set_payload(json_data)
        container.attach(json_part)

        ctype, encoding = mimetypes.guess_type(filename)
        if ctype:
            maintype, subtype = ctype.split("/", 1)
        else:
            maintype, subtype = "application", "binary"
        blob_part = MIMEBase(maintype, subtype)
        blob_part.add_header("Content-ID", "input")
        blob_part.add_header("Content-Transfer-Encoding", "binary")
        blob_part.add_header("Content-Disposition", "attachment;filename=%s" % filename)

        blob_part.set_payload(blob)
        container.attach(blob_part)

        # Create data by hand :(
        boundary = "====Part=%s=%s===" % (time.time, random.randint(0, 1000000000))
        headers = {
            "Accept": "application/json+nxentity, */*",
            "Authorization": self.auth,
            "Content-Type": 'multipart/related;boundary="%s";type="application/json+nxrequest";start="request"'
            % boundary,
        }
        data = (
            "--"
            + boundary
            + "\r\n"
            + json_part.as_string()
            + "\r\n"
            + "--"
            + boundary
            + "\r\n"
            + blob_part.as_string()
            + "\r\n"
            + "--"
            + boundary
            + "--"
        )

        req = urllib2.Request(self.root + "Blob.Attach", data, headers)
        try:
            resp = self.opener.open(req)
        except Exception, e:
            self._handle_error(e)
            raise
Exemple #3
0
    def _attach_blob(self, blob, **params):
        ref = params['document']
        filename = os.path.basename(ref)

        container = MIMEMultipart("related",
                type="application/json+nxrequest",
                start="request")

        d = {'params': params}
        json_data = json.dumps(d, sort_keys=True)
        json_part = MIMEBase("application", "json+nxrequest")
        json_part.add_header("Content-ID", "request")
        json_part.set_payload(json_data)
        container.attach(json_part)

        ctype, encoding = mimetypes.guess_type(filename)
        if ctype:
            maintype, subtype = ctype.split('/', 1)
        else:
            maintype, subtype = "application", "binary"
        blob_part = MIMEBase(maintype, subtype)
        blob_part.add_header("Content-ID", "input")
        blob_part.add_header("Content-Transfer-Encoding", "binary")
        blob_part.add_header("Content-Disposition",
            "attachment;filename=%s" % filename)

        blob_part.set_payload(blob)
        container.attach(blob_part)

        # Create data by hand :(
        boundary = "====Part=%s=%s===" % (time.time, random.randint(0, 1000000000))
        headers = {
                "Accept": "application/json+nxentity, */*",
                "Authorization": self.auth,
                "Content-Type": 'multipart/related;boundary="%s";type="application/json+nxrequest";start="request"'
                    % boundary,
        }
        data = "--" + boundary + "\r\n" \
                + json_part.as_string() + "\r\n" \
                + "--" + boundary + "\r\n" \
                + blob_part.as_string() + "\r\n" \
                + "--" + boundary + "--"

        req = urllib2.Request(self.root + "Blob.Attach", data, headers)
        try:
            resp = self.opener.open(req)
        except Exception, e:
            self._handle_error(e)
            raise
def SendEmail(EmailAdress, text, SearchPoint):
    me = '*****@*****.**'
    you = EmailAdress
    contents = "검색기준주소: " + SearchPoint + "\n\n가까운대피소 검색 결과: \n" + text

    naver_server = smtplib.SMTP_SSL('smtp.naver.com', 465)
    naver_server.login('jysso3070', 'dbswntn3030')

    msg = MIMEBase('multipart', 'mixed')

    cont = MIMEText(contents)
    cont['Subject'] = '스크립트언어'
    cont['From'] = me
    cont['To'] = you

    msg.attach(cont)

    path = 'nearSearch.html'
    part = MIMEBase("application", "octet-stream")
    part.set_payload(open(path, 'rb').read())

    encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(path))

    msg.attach(part)
    naver_server.sendmail(me, you, msg.as_string())
    naver_server.quit()
Exemple #5
0
def mail_send(mail_token,
              to,
              sub_text,
              msg_text="",
              html_return="",
              file_return=""):
    mail_server = smtplib.SMTP('smtp.gmail.com', 587)
    mail_server.ehlo()  # say Hello
    mail_server.starttls()  # TLS 사용시 필요
    mail_server.login(mail_token[0], mail_token[1])

    # # 기본 메일 주소
    msg = MIMEBase('multipart', 'mixed')
    msg['Subject'] = sub_text
    msg['To'] = to

    #메시지
    if msg_text != "":
        text = MIMEText(msg_text)
        msg.attach(text)

    #불러온 HTML 파일 임포트
    if html_return != "":
        msg.attach(html_return)

    #미리 불러온 첨부파일 임포트
    if file_return != "":
        msg.attach(file_return)

    mail_server.sendmail(mail_token[0], to, msg.as_string())

    mail_server.quit()
def SendMail(add):
    host = "smtp.gmail.com" # Gmail STMP 서버 주소.
    port = "587"
    htmlFileName = "logo.html"

    senderAddr = "*****@*****.**"     # 보내는 사람 email 주소.
    recipientAddr = add               # 받는 사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "경기지역화폐 가맹점 안내"

    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    # MIME 문서를 생성합니다.
    htmlFD = open(htmlFileName, 'rb')
    HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
    htmlFD.close()

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    msg.attach(HtmlPart)
    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host,port)
    #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**","ghd3425849") #여기에 비밀번호 써야 된다.
    s.sendmail(senderAddr , [recipientAddr], msg.as_string())
    s.close()
Exemple #7
0
def sendMail(addr, text, name, mapCheck, r, c):
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(myEmail, myPassword)

    msg = MIMEBase('multipart', 'mixed')
    msg['Subject'] = "[" + name + "] 병원 상세 정보 및 지도"
    msg['From'] = myEmail
    msg['To'] = addr

    if mapCheck == 1:
        path = name + ".png"
        if os.path.isfile(path) == False:
            openMap.saveMap(r, c, name)
        image = open(path, 'rb')
        imageP = MIMEImage(image.read())
        image.close()
        msg.attach(imageP)

    cont = MIMEText(text)
    if mapCheck == 1:
        imageP.add_header('Content-Disposition', 'attachment', filename=path)
    msg.attach(cont)
    s.sendmail(myEmail, addr, msg.as_string())
    s.quit()
Exemple #8
0
def SendingMail(content):
    host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
    port = "587"

    senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
    recipientAddr = "*****@*****.**"  # 받는 사람 email 주소.

    msgtext = "testing now"
    passwd = "rlfrkaptnl"

    html = MakeHtmlDoc(DataList)

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "공연/전시 세부 정보"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    msgPart = MIMEText(msgtext, 'plain')
    perforPart = MIMEText(html, 'html', _charset='UTF-8')

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    # 메세지에 생성한 MIME 문서를 첨부합니다.
    msg.attach(msgPart)
    msg.attach(perforPart)

    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host, port)
    #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(senderAddr, passwd)
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
def sendMail():
    import mimetypes
    import smtplib
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText

    host = "smtp.gmail.com"
    port = "587"

    msg = MIMEBase("multipart", "alternative")

    msgtext = RenderText1.get(0.0, END)
    senderAddr = "*****@*****.**"
    recipientAddr = "*****@*****.**"

    msg['Subject'] = "국가기술자격증 상세 안내"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    msgPart = MIMEText(msgtext, 'plain')
    msg.attach(msgPart)

    s = smtplib.SMTP(host, port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "a786s156!@#")
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
Exemple #10
0
def sendMail(MailDestination, MailContents, MailSubject):
    #global value
    host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
    port = "587"
    # htmlFileName = "logo.html"

    senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
    recipientAddr = MailDestination  # 받는 사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "학술지 - " + MailSubject
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    # MIME 문서를 생성합니다.
    # htmlFD = open(htmlFileName, 'rb')
    # HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
    HtmlPart = MIMEText(MailContents, _charset='UTF-8')
    # htmlFD.close()

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    msg.attach(HtmlPart)

    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host, port)
    #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "l1199328")
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
Exemple #11
0
def gmail_attach_file(_from,
                      _passwd,
                      to_list,
                      subject,
                      content,
                      file_chunk_map,
                      host='smtp.gmail.com',
                      port=587):
    outer = MIMEBase('multipart', 'mixed')
    outer['Subject'] = Header(subject.encode('utf-8'), 'utf-8')
    outer['From'] = _from
    outer['To'] = ', '.join(to_list)
    outer.preamble = 'This is a multi-part message in MIME format.\n\n'
    outer.epilogue = ''
    msg = MIMEText(content.encode('utf-8'), _charset='utf-8')
    outer.attach(msg)

    for file, chunk in file_chunk_map.items():
        ctype, encoding = guess_type(file)
        maintype, subtype = ctype.split('/', 1)
        msg = MIMEApplication(chunk, _subtype=subtype)
        msg.add_header('Content-Disposition', 'attachment', filename=file)
        outer.attach(msg)

    s = smtplib.SMTP(host, port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(_from, _passwd)
    s.sendmail(_from, to_list, outer.as_string())
    return s.quit()
Exemple #12
0
def sendmail(addr, html):
    global host, port
    senderAddr = "*****@*****.**"
    recipientAddr = addr
    msgtext = ''

    msg = MIMEBase('multipart', 'alternative')

    msg['Subject'] = "[E-Class(공개강의 검색 엔진)] 북마크 목록을 전송해드립니다."
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    HtmlPart = MIMEText(html, 'html', _charset='UTF-8')

    msg.attach(HtmlPart)

    print("connect smtp server ... ")
    s = smtplib.SMTP(host, port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "dkssud110112")
    try:
        s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    except:
        print("사망각")
        s.close()
        return False
    else:
        print("Mail sending complete!!!")
        s.close()
        return True
Exemple #13
0
def _send_email(payload):
    is_succeed = False
    sender = settings.SENDER_EMAIL
    password = settings.SENDER_PASSWORD

    name = payload.get('name')
    receiverMail = payload.get('receiveMail')
    currency = payload.get('currency')
    current_price = payload.get('current_price')
    low_price = payload.get('low_price')
    msg = MIMEBase('multipart', 'alternative')

    msg['Subject'] = 'gmail send test'
    msg['From'] = sender
    msg['To'] = receiverMail

    #TODO payload 데이터 가공하여 _contents 로 전달
    html = _contents(name, currency, current_price, low_price)

    html_text = MIMEText(html, 'html')
    msg.attach(html_text)
    s = smtplib.SMTP(HOST, PORT)

    try:
        s.starttls()
        s.login(sender, password)
        s.sendmail(sender, [receiverMail], msg.as_string())
        is_succeed = True
    except:
        is_succeed = False
    finally:
        s.close()

    return is_succeed
def Email():
    # global value
    host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
    port = "587"
    htmlFileName = "AirInfo.html"

    senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
    recipientAddr = "*****@*****.**"  # 받는 사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "대기상태 정보"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    # MIME 문서를 생성합니다.
    htmlFD = open(htmlFileName, 'rb')
    HtmlPart = MIMEText(htmlFD.read(), 'html', _charset='UTF-8')
    htmlFD.close()

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    msg.attach(HtmlPart)

    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host, port)
    # s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "wlsaud94")
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
def sendmail(gmail_sender, gmail_recipient, gmail_passwd, subject, filename): # https://hwangyoungjae.tistory.com/118
    try:
        msg = MIMEBase("multipart", "mixed")
        msg['Subject'] = subject
        msg['From'] = gmail_sender
        msg['To'] = gmail_recipient

        # Make MINEType
        file = open(filename, 'rb')
        filepart = MIMEText(file.read(), _charset='UTF-8')
        file.close()

        # 만들었던 mime을 MIMEBase에 첨부
        msg.attach(filepart)

        # 첨부파일에 대한 정보 추가
        msg.add_header('Content-Disposition', 'attachment', filename=filename)

        mailserver = smtplib.SMTP('smtp.gmail.com', 587) # STMP name, STMP port
        mailserver.ehlo() # say hello
        mailserver.starttls() # TLS 보안 시작
        mailserver.login(gmail_sender, gmail_passwd)
        mailserver.sendmail(gmail_sender, [gmail_recipient], msg.as_string()) # 메일 발송
        mailserver.close()
        print("메일을 전송 완료하였습니다.")
    except:
        print("메일 전송이 실패하였습니다.")
Exemple #16
0
    def sendEmail(self):
        host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
        port = "587"
        #htmlFileName = "logo.html"

        senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
        recipientAddr = self.entry_emailInsert.get()  # 받는 사람 email 주소.

        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = self.entry_summoner_name.get(
        ) + "님의 리그오브레전드 전적 검색 정보입니다."
        msg['From'] = senderAddr
        msg['To'] = recipientAddr

        ## MIME 문서를 생성합니다.
        #htmlFD = open(htmlFileName, 'rb')
        #HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
        #htmlFD.close()
        HtmlPart = MIMEText(self.text_records.get(1.0, END))

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(HtmlPart)

        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host, port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**", "5080700g")
        s.sendmail(senderAddr, [recipientAddr], msg.as_string())
        s.close()
Exemple #17
0
def send_email(account):
    # 메세지 내용
    msg = MIMEBase("multipart", "mixed")
    msg['Subject'] = '제목 테스트'
    htmlBody = render_template('renderMailAuth.html', user_id=account.user_id)

    # htmlFD = open('renderMailAuth.html', 'rb')
    HtmlPart = MIMEText(htmlBody, 'html', _charset='UTF-8')
    # htmlFD.close()

    msg.attach(HtmlPart)

    # 세션 생성
    # smtplib.SMTP(SMTP변수, 포트번호)
    s = smtplib.SMTP('smtp.gmail.com', 587)
    # TLS보안 설정
    s.starttls()
    # 로그인 인증
    # s.login('지메일계정','앱비밀번호')
    s.login('', '')
    # 메일 보내기
    # s.sendmail('보내는메일주소','받는메일주소',메세지내용)
    s.sendmail('', account.email, msg.as_string().encode("UTF-8"))
    print('메일보내기 성공')
    # 세션종료
    s.quit()
Exemple #18
0
    def SendMail(self):
        host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
        port = "587"
        imgFile='screenshot.png.png'

        senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
        recipientAddr = "*****@*****.**"  # 받는 사람 email 주소.

        msg = MIMEBase("multipart", "mixed")
        msg['Subject'] = "지진 대피소"  # 제목
        msg['From'] = senderAddr
        msg['To'] = recipientAddr

        cont=MIMEText(self.address,'plain','UTF-8')
        msg.attach(cont)

        fp=open(imgFile,'rb')
        img=MIMEImage(fp.read())
        fp.close()
        msg.attach(img)

        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host, port)
        # s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**", "qaz067808")
        s.sendmail(senderAddr, [recipientAddr], msg.as_string())
        s.close()
Exemple #19
0
    def sendEmail(self):
        host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
        port = "587"
        htmlFile=self.MakeHtmlDoc() #예쁘게 보내주려고 html 파일로 변환
        senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
        recipientAddr = urllib.parse.quote(self.email_entry.get()).replace("%40","@")    # 받는 사람 email 주소.

        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "["+str(date.today())+"] 현재까지 읽은 책 목록 ♨"
        msg['From'] = senderAddr
        msg['To'] = recipientAddr

        # MIME 문서를 생성합니다.
        HtmlPart = MIMEText(htmlFile,'html', _charset='UTF-8')

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(HtmlPart)

        # 메일을 발송한다.
        s = smtplib.SMTP(host, port)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**", "ghd5683734")
        s.sendmail(senderAddr, [recipientAddr], msg.as_string())
        s.close()
        Sounds.따라란()
def SendGmail(Address, Message):
    # global value
    host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
    port = "587"
    htmlFileName = "logo.html"

    senderAddr = "*****@*****.**"  # 보내는 사람 email 주소.
    recipientAddr = Address  # 받는 사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "Kuide"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    # MIME 문서를 생성합니다.
    HtmlPart = MIMEText(Message, _charset='UTF-8')

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    msg.attach(HtmlPart)

    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host, port)
    # s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "qwer!@#$980827")
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
def sendEmail(module, data, id, server):
    htmlText = buildHtmlTable(data)
    print("debug message:", htmlText)

    # SMTP 서버의 주소와 포트 번호
    host = "smtp.gmail.com"
    port = 587

    # 받는 사람의 이메일
    recipientAddr = id + "@" + server

    # 보내는 사람의 이메일과 비밀번호
    senderAddr = decryptFileContext(module, "./Data/resource/serviceEmailID.bin")
    senderPW = decryptFileContext(module, "./Data/resource/serviceEmailPW.bin")
    if (senderAddr is None) or (senderPW is None):
        return err_EMAIL_DECRYPT_FAILED

    msg = MIMEBase("multipart", "mixed")
    msg["Subject"] = "\"거기 공기 어때?\"에서 요청한 대기오염측정정보입니다."
    msg["From"] = senderAddr
    msg["To"] = recipientAddr

    htmlPart = MIMEText(htmlText, "html", "UTF-8")
    msg.attach(htmlPart)

    try:
        smtp = smtplib.SMTP(host=host, port=port)
        smtp.starttls()
        smtp.login(senderAddr, senderPW)
        smtp.sendmail(senderAddr, [recipientAddr], msg.as_string())
        smtp.close()
    except:
        print("error message: Email sending failed")
        return err_EMAIL_SEND_FAILED
    return EMAIL_SUCCESS
Exemple #22
0
def send(ti, Addr, data):
    host = "smtp.gmail.com"  # Gmail SMTP 서버 주소.
    port = "587"

    title = ti
    senderAddr = "*****@*****.**"  # senderAddr = str(input ('보내는 메일 주소 :'))
    recipientAddr = Addr
    passwd = "scriptlanguage"  # str(input ('보내는 메일 주소의 비밀번호 :'))

    msg = MIMEBase("multipart", 'alternative')  # Message container를 생성
    msg['Subject'] = title  # set message
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    htmlFD = open(mail_data(data), 'rb')
    htmlPart = MIMEText(htmlFD.read(), 'html', _charset='utf-8')
    htmlFD.close()

    msg.attach(htmlPart)  # 메세지에 생성한 MIME 문서를 첨부합니다
    print("SMTP 서버에 연결 중 ... ")
    s = smtplib.SMTP(host, port)  # python3.5에서는 smtplib.SMTP(host,port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(senderAddr, passwd)  # 로그인
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
    print("메일을 전송하였습니다.")
Exemple #23
0
    def encrypt(self, gpg, keys):
        if self.is_encrypted():
            return

        payload = MIMEBase(self._message.get_content_maintype(), self._message.get_content_subtype())
        payload.set_charset(self._message.get_charset())
        payload.set_payload(self._message.get_payload())
        payload.set_boundary(self._message.get_boundary())
        self._mime_encrypt(payload.as_string(), gpg, keys)
Exemple #24
0
 def test_mime_text_plain(self):
     """Mime message of type text/plain is ignored without warning"""
     self.mocker.replay()
     ci = cloudinit.CloudInit()
     message = MIMEBase("text", "plain")
     message.set_payload("Just text")
     ci.datasource = FakeDataSource(message.as_string())
     ci.consume_userdata()
     self.assertEqual("", self.log_file.getvalue())
Exemple #25
0
    def Send(self):
        recipientAddr = self.id_input.get()  # 받는 사람 email 주소.
        if recipientAddr == "":
            return
        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "해가 뜰때까지에서 보내드립니다"
        msg['From'] = senderAddr
        msg['To'] = recipientAddr
        self.suninfo = Suninfo(self.location,
                               self.travel_date.strftime("%Y%m%d"))
        longitude = self.suninfo.LoadLongitude()
        latitude = self.suninfo.LoadLatitude()
        tw_civil = self.suninfo.LoadTimes(
            Suninfo.CategoryDict["시민박명(아침)"]) + self.suninfo.LoadTimes(
                Suninfo.CategoryDict["시민박명(저녁)"])
        tw_naut = self.suninfo.LoadTimes(
            Suninfo.CategoryDict["항해박명(아침)"]) + self.suninfo.LoadTimes(
                Suninfo.CategoryDict["항해박명(저녁)"])
        tw_ast = self.suninfo.LoadTimes(
            Suninfo.CategoryDict["천문박명(아침)"]) + self.suninfo.LoadTimes(
                Suninfo.CategoryDict["천문박명(저녁)"])

        time1 = self.suninfo.LoadTimes(Suninfo.CategoryDict["일출"])
        time2 = self.suninfo.LoadTimes(Suninfo.CategoryDict["일중"])
        time3 = self.suninfo.LoadTimes(Suninfo.CategoryDict["일몰"])

        msgtext = '''
                날짜 : {0} , 지역 : {1}
                위치: 동경 {2}도{3}분 / 북위 {4}도{5}분
                
                박명시간
                시민박명(아침/저녁) :  아침-{6}시{7}분  /  저녁- {8}시{9}분
                항해박명(아침/저녁) : 아침-{10}시{11}분  /  저녁- {12}시{13}분
                천문박명(아침/저녁) : 아침-{14}시{15}분  /  저녁- {16}시{17}분
                
                해뜨는 시각(일출) : {18}시 {19}분
                한낮의 시각(남중) : {20}시 {21}분
                해지는 시각(일몰) : {22}시 {23}분
            '''.format(self.travel_date.strftime("%Y-%m-%d"), self.location,
                       longitude[0], longitude[1], latitude[0], latitude[1],
                       tw_civil[0], tw_civil[1], tw_civil[2], tw_civil[3],
                       tw_naut[0], tw_naut[1], tw_naut[2], tw_naut[3],
                       tw_ast[0], tw_ast[1], tw_ast[2], tw_ast[3], time1[0],
                       time1[1], time2[0], time2[1], time3[0], time3[1])
        msgPart = MIMEText(msgtext, 'plain')

        msg.attach(msgPart)

        # 메일을 발송한다.
        s = smtplib.SMTP(host, port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**", "undugy98")
        s.sendmail("*****@*****.**", [recipientAddr], msg.as_string())
        s.close()
 def test_mime_text_plain(self):
     """Mime message of type text/plain is ignored without warning"""
     self.mocker.replay()
     ci = cloudinit.CloudInit()
     message = MIMEBase("text", "plain")
     message.set_payload("Just text")
     ci.datasource = FakeDataSource(message.as_string())
     ci.consume_userdata()
     self.assertEqual("", self.log_file.getvalue())
Exemple #27
0
    def AddItem(self, subject, msg = ''):
        f =  MIMEBase('MsgItem', 'item')
        f['Subject'] = Header(subject, 'UTF-8')
        f['From']    = self.user
        f['To']      = self.user
        f.set_payload(msg)
        encode_base64(f)

        print  self.imap.append(self.folder, f.as_string())
def send_mail(senderAddr, password, recipientAddr, maildatalist, mailflag):

    s = smtplib.SMTP("smtp.gmail.com", 587)  # SMTP 서버 설정
    s.ehlo()
    s.starttls()  # STARTTLS 시작
    s.ehlo()
    s.login(senderAddr, password)

    msg = MIMEBase("multipart", "alternative")

    msg['Subject'] = '대기현황'
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    topic = ''

    for data in maildatalist:
        if mailflag == 0 or mailflag == 1 or mailflag == 4:
            topic = data.year + '년 ' + data.month + '월 ' + data.date + '일 ' + data.hour + '시 ' + data.station + '의 대기 현황'
        elif mailflag == 2:
            topic = data.station + '의' + data.year + '년 ' + data.month + '월 ' + data.date + '일 평균 대기 현황'
        elif mailflag == 3:
            topic = data.station + '의' + data.year + '년 ' + data.month + '월 평균 대기 현황'
        part1 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part1)

        topic = '아황산 : {0:.3f} ppm'.format(data.so2)
        part2 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part2)

        topic = '일산화탄소 : {0:.3f} ppm'.format(data.co)
        part3 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part3)

        topic = '오존 : {0:.3f} ppm'.format(data.o3)
        part4 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part4)

        topic = '이산화질소 : {0:.3f} ppm'.format(data.no2)
        part5 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part5)

        topic = '미세먼지 : ' + str(data.pm10) + '㎍/㎥'
        part6 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part6)

        topic = '초미세먼지 : ' + str(data.pm25) + '㎍/㎥'
        part7 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part7)

        topic = ''
        part8 = MIMEText(topic, 'html', _charset='UTF-8')
        msg.attach(part8)

    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
Exemple #29
0
def sendmail(account: EmailAccount, to_addrs: t.List[str], msg: MIMEBase):
    s = smtplib.SMTP(account.server, account.port)
    s.starttls()
    # print(f"logging in as '{account.username}, using password: '******'...'")
    s.login(account.username, account.password)
    msg['From'] = account.email
    # msg['To'] = to_addrs # TODO: is this even necessary ?

    s.sendmail(account.email, to_addrs, msg.as_string())
    s.quit()
Exemple #30
0
def Send(recipientAddr, Toilet):
    #global value
    host = "smtp.gmail.com"  # Gmail STMP 서버 주소
    port = "587"
    htmlFileName = "message.html"

    senderAddr = "*****@*****.**"  # 보내는사람 email 주소.
    #recipientAddr = "*****@*****.**"   # 받는사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "똥 터 에서 보내드립니다"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    msg.attach(MIMEText("이름 : " + Toilet['PBCTLT_PLC_NM']))
    if Toilet['OPEN_TM_INFO'] == None:
        msg.attach(MIMEText("개방시간 : 미정"))
    else:
        msg.attach(MIMEText("개방시간 : " + Toilet['OPEN_TM_INFO']))
    if Toilet['MANAGE_INST_TELNO'] == None:
        msg.attach(MIMEText("전화번호 : 없음"))
    else:
        msg.attach(MIMEText("전화번호 : " + Toilet['MANAGE_INST_TELNO']))
    msg.attach(MIMEText("남녀공용 : " + Toilet['MALE_FEMALE_TOILET_YN']))

    msg.attach(MIMEText("메모"))
    try:
        f = open('Asset/txt/' + Toilet['SIGUN_NM'] + '.txt', "r")
    except:
        pass

    for line in f:
        if line.startswith(Toilet['PBCTLT_PLC_NM']):
            line = f.readline()
            line = line.replace('\+n', '\n')
            msg.attach(MIMEText(line))

    # 보낼 문서를 생성합니다
    # htmlFD = open(htmlFileName, 'rb')
    # HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
    # htmlFD.close()

    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    #msg.attach(HtmlPart)

    # 메일을 발송한다
    s = mysmtplib.MySMTP(host, port)
    #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "yurisoletminju-1")
    s.sendmail(senderAddr, [recipientAddr], msg.as_string())
    s.close()
Exemple #31
0
 def test_mime_text_plain_shell(self):
     """Mime type text/plain starting #!/bin/sh is treated as script"""
     script = "#!/bin/sh\necho hello\n"
     outpath = cloudinit.get_ipath_cur("scripts") + "/part-001"
     self.mock_write(outpath, script, 0700)
     self.mocker.replay()
     ci = cloudinit.CloudInit()
     message = MIMEBase("text", "plain")
     message.set_payload(script)
     ci.datasource = FakeDataSource(message.as_string())
     ci.consume_userdata()
     self.assertEqual("", self.log_file.getvalue())
def EmailButtonAction():         # 이메일버튼 누름
    global startClick
    if startClick == 1:
        import mysmtplib
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText

        global recipentMail
        global InputLabel
        global searchStatus
        host = "smtp.gmail.com"  # your smtp address
        port = "587"
        htmlFileName = "logo.html"

        sendMail = "*****@*****.**"
        recipientMail = receiveEmailLabel.get()
        msgtext = "당신의 검색결과 입니다."

        # 헤더에 첨부 파일에 대한 정보를 추가 시킨다.
        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "전국 고속도로 LPG 주유소 검색"
        msg['From'] = sendMail
        msg['To'] = recipientMail

        html = MakeHtmlDoc(SearchHighwayTitle(InputLabel.get()))

        msgPart = MIMEText(msgtext, 'plain')
        oilPart = MIMEText(html, 'html', _charset = 'UTF-8')

        # MIME 문서를 생성합니다.
        htmlFD = open(htmlFileName, 'rb')
        HtmlPart = MIMEText(htmlFD.read(), 'html', _charset='UTF-8')
        htmlFD.close()

        # 메세지에 생성한 MIME 문서를 첨부합니다.
        msg.attach(HtmlPart)
        msg.attach(msgPart)
        msg.attach(oilPart)

        # 메일을 발송한다.
        print ("connect smtp server ... ")
        s = mysmtplib.MySMTP(host, port)

        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**","9692gyawkd")
        s.sendmail(sendMail , [recipientMail], msg.as_string())
        s.close()

        messagebox.showinfo(title="완료", message="최근 고속도로 명 결과가 메일로 전송되었습니다.")
    else:
        messagebox.showinfo(title="주의!", message="고속도로 명을 검색 하고 난 뒤에 눌러주세요.")
 def test_mime_text_plain_shell(self):
     """Mime type text/plain starting #!/bin/sh is treated as script"""
     script = "#!/bin/sh\necho hello\n"
     outpath = cloudinit.get_ipath_cur("scripts") + "/part-001"
     self.mock_write(outpath, script, 0700)
     self.mocker.replay()
     ci = cloudinit.CloudInit()
     message = MIMEBase("text", "plain")
     message.set_payload(script)
     ci.datasource = FakeDataSource(message.as_string())
     ci.consume_userdata()
     self.assertEqual("", self.log_file.getvalue())
Exemple #34
0
def sendMail(mvDictData, sender, passWd,recipient):
    # mvDictData -> HTML

    impl = getDOMImplementation()
    newdoc = impl.createDocument(None, "html", None)
    topElement = newdoc.documentElement
    header = newdoc.createElement('header')
    topElement.appendChild(header)
    body = newdoc.createElement('body')
    for k, v in mvDictData.items():
        b = newdoc.createElement('b')
        bText = newdoc.createTextNode(k)
        b.appendChild(bText)
        body.appendChild(b)
        br = newdoc.createElement('br')
        body.appendChild(br)
        if v.__class__ == type(list()):
            if k == "posters":
                for x in v:
                    p = newdoc.createElement('img src'+'='+x)
            else:
                for x in v:
                    p = newdoc.createElement('p')
                    pText = newdoc.createTextNode(x)
                    p.appendChild(pText)
        else:
            p = newdoc.createElement('p')
            pText = newdoc.createTextNode(v)
            p.appendChild(pText)
        body.appendChild(p)
        body.appendChild(br)
    topElement.appendChild(body)
    html = newdoc.toxml()

    host = sender.rpartition('@')
    host = "smtp." + host[2]
    port = "587"
    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "[" + mvDictData["title"] + "] Movie Imformation"
    msg['From'] = sender
    msg['To'] = recipient
    htmlPart = MIMEText(html,'html', _charset = 'UTF-8')

    msg.attach(htmlPart)

    s = smtplib.SMTP(host, port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(sender, passWd)
    s.sendmail(sender, recipient, msg.as_string())
    s.close()
Exemple #35
0
    def send(self):
        import http.client
        import mysmtplib
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText

        #global value
        host = "smtp.gmail.com"  # Gmail STMP 서버 주소.
        port = "587"
        htmlFileName = "logo.html"

        #get data from e-mail gui
        number = self.input_email_number.toPlainText()  # 객체번호
        sender = self.input_email_sender.toPlainText()  # 보내는 사람 email 주소.
        password = self.input_email_password.toPlainText()  # 패스워드.
        target = self.input_email_target.toPlainText()  # 받는 사람 email 주소.

        #get xml from object number
        key = "VZwF3B6OId9MZtOCoLO8pS5FCjIXGQj3MYkPenIahW0vcGzgC%2Bb8rJHcYoDRPk%2Fc9dsbldkOhJi0mBewN4UBMg%3D%3D"
        conn = http.client.HTTPConnection("data.ekape.or.kr")
        conn.request(
            "GET",
            "/openapi-data/service/user/animalTrace/traceNoSearch?ServiceKey="
            + key + "&traceNo=" + number)  #서버에 GET 요청

        req = conn.getresponse()  #openAPI 서버에서 보내온 요청을 받아옴
        cLen = bytearray(req.getheader("Content-Length"), 'utf-8')  #가져온 데이터 길이

        if int(req.status) == 200:
            strXml = (req.read().decode('utf-8'))

        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "Animal Husbandry Management xml - " + number
        msg['From'] = sender
        msg['To'] = target

        # MIME 문서를 생성합니다.
        htmlPart = MIMEText(str(strXml), 'html', _charset='UTF-8')

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(htmlPart)

        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host, port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(sender, password)
        s.sendmail(sender, [target], msg.as_string())
        s.close()
Exemple #36
0
def sendGmail(bookmark):
#global value
    host = "smtp.gmail.com" # Gmail STMP 서버 주소.
    port = "587"
    htmlFileName = "logo.html"

    senderAddr = "*****@*****.**"     # 보내는 사람 email 주소.
    recipientAddr = "*****@*****.**"   # 받는 사람 email 주소.

    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "Movie"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr

    # MIME 문서를 생성합니다.
    info_dic = bookmark
    info_str = ''
    theater_dic = list()

    for n in range(len(info_dic)):
        theater_dic = theater_info.GetMovieInfo(info_dic[n])['info']

        if theater_dic:
            info_str = '['+str(info_dic[n]['name'])+']'
            MovieHtmlPart = MIMEText(info_str, 'html', _charset='UTF-8')
            msg.attach(MovieHtmlPart)
            for i in range(len(theater_dic)):
                info_str = '○' + theater_dic[i]['movie'] + ' :'
                for n in range(len(theater_dic[i]['time'])):
                    info_str += ' [' + theater_dic[i]['time'][n] + ']'
                MovieHtmlPart = MIMEText(info_str, 'html', _charset='UTF-8')
                msg.attach(MovieHtmlPart)
        info_str = ''
        MovieHtmlPart = MIMEText(info_str, 'html', _charset='UTF-8')
        msg.attach(MovieHtmlPart)
        theater_dic.clear()

    #MovieHtmlPart = MIMEText(info_str, 'html', _charset = 'UTF-8' )
    #msg.attach(MovieHtmlPart)
    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    #msg.attach(MovieHtmlPart)

    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host,port)
    #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "")
    s.sendmail(senderAddr , [recipientAddr], msg.as_string())
    s.close()
Exemple #37
0
    def send(self):
        import http.client
        import mysmtplib
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText

        #global value
        host = "smtp.gmail.com" # Gmail STMP 서버 주소.
        port = "587"
        htmlFileName = "logo.html"

        #get data from e-mail gui
        number = self.input_email_number.toPlainText()     # 객체번호
        sender = self.input_email_sender.toPlainText()     # 보내는 사람 email 주소.
        password = self.input_email_password.toPlainText() # 패스워드.
        target = self.input_email_target.toPlainText()     # 받는 사람 email 주소.
        
        #get xml from object number
        key = "VZwF3B6OId9MZtOCoLO8pS5FCjIXGQj3MYkPenIahW0vcGzgC%2Bb8rJHcYoDRPk%2Fc9dsbldkOhJi0mBewN4UBMg%3D%3D"
        conn = http.client.HTTPConnection("data.ekape.or.kr")
        conn.request("GET", "/openapi-data/service/user/animalTrace/traceNoSearch?ServiceKey=" + key + "&traceNo=" + number) #서버에 GET 요청 

        req = conn.getresponse()    #openAPI 서버에서 보내온 요청을 받아옴
        cLen = bytearray(req.getheader("Content-Length"), 'utf-8')    #가져온 데이터 길이

        if int(req.status) == 200 :
            strXml = (req.read().decode('utf-8'))
            
        
        
        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "Animal Husbandry Management xml - " + number
        msg['From'] = sender
        msg['To'] = target

        # MIME 문서를 생성합니다.
        htmlPart = MIMEText(str(strXml), 'html', _charset = 'UTF-8')

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(htmlPart)

        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host,port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(sender, password)
        s.sendmail(sender, [target], msg.as_string())
        s.close()
Exemple #38
0
    def test_mime_text_plain(self):
        """Mime message of type text/plain is ignored but shows warning."""
        ci = stages.Init()
        message = MIMEBase("text", "plain")
        message.set_payload("Just text")
        ci.datasource = FakeDataSource(message.as_string().encode())

        with mock.patch('cloudinit.util.write_file') as mockobj:
            log_file = self.capture_log(logging.WARNING)
            ci.fetch()
            ci.consume_data()
            self.assertIn("Unhandled unknown content-type (text/plain)",
                          log_file.getvalue())
        mockobj.assert_called_once_with(ci.paths.get_ipath("cloud_config"), "",
                                        0o600)
Exemple #39
0
    def test_mime_text_plain(self):
        """Mime message of type text/plain is ignored but shows warning."""
        ci = stages.Init()
        message = MIMEBase("text", "plain")
        message.set_payload("Just text")
        ci.datasource = FakeDataSource(message.as_string())

        mock_write = self.mocker.replace("cloudinit.util.write_file", passthrough=False)
        mock_write(ci.paths.get_ipath("cloud_config"), "", 0600)
        self.mocker.replay()

        log_file = self.capture_log(logging.WARNING)
        ci.fetch()
        ci.consume_userdata()
        self.assertIn("Unhandled unknown content-type (text/plain)", log_file.getvalue())
    def test_mime_text_plain(self):
        """Mime message of type text/plain is ignored but shows warning."""
        ci = stages.Init()
        message = MIMEBase("text", "plain")
        message.set_payload("Just text")
        ci.datasource = FakeDataSource(message.as_string().encode())

        with mock.patch('cloudinit.util.write_file') as mockobj:
            log_file = self.capture_log(logging.WARNING)
            ci.fetch()
            ci.consume_data()
            self.assertIn(
                "Unhandled unknown content-type (text/plain)",
                log_file.getvalue())
        mockobj.assert_called_once_with(
            ci.paths.get_ipath("cloud_config"), "", 0o600)
    def test_mime_application_octet_stream(self):
        """Mime type application/octet-stream is ignored but shows warning."""
        ci = stages.Init()
        message = MIMEBase("application", "octet-stream")
        message.set_payload(b'\xbf\xe6\xb2\xc3\xd3\xba\x13\xa4\xd8\xa1\xcc')
        encoders.encode_base64(message)
        ci.datasource = FakeDataSource(message.as_string().encode())

        with mock.patch('cloudinit.util.write_file') as mockobj:
            log_file = self.capture_log(logging.WARNING)
            ci.fetch()
            ci.consume_data()
            self.assertIn(
                "Unhandled unknown content-type (application/octet-stream)",
                log_file.getvalue())
        mockobj.assert_called_once_with(
            ci.paths.get_ipath("cloud_config"), "", 0o600)
Exemple #42
0
    def test_mime_text_plain_shell(self):
        """Mime type text/plain starting #!/bin/sh is treated as script."""
        ci = stages.Init()
        script = "#!/bin/sh\necho hello\n"
        message = MIMEBase("text", "plain")
        message.set_payload(script)
        ci.datasource = FakeDataSource(message.as_string())

        outpath = os.path.join(ci.paths.get_ipath_cur("scripts"), "part-001")
        mock_write = self.mocker.replace("cloudinit.util.write_file", passthrough=False)
        mock_write(outpath, script, 0700)
        mock_write(ci.paths.get_ipath("cloud_config"), "", 0600)
        self.mocker.replay()

        log_file = self.capture_log(logging.WARNING)
        ci.fetch()
        ci.consume_userdata()
        self.assertEqual("", log_file.getvalue())
Exemple #43
0
    def test_mime_text_plain_shell(self):
        """Mime type text/plain starting #!/bin/sh is treated as script."""
        ci = stages.Init()
        script = "#!/bin/sh\necho hello\n"
        message = MIMEBase("text", "plain")
        message.set_payload(script)
        ci.datasource = FakeDataSource(message.as_string())

        outpath = os.path.join(ci.paths.get_ipath_cur("scripts"), "part-001")

        with mock.patch('cloudinit.util.write_file') as mockobj:
            log_file = self.capture_log(logging.WARNING)
            ci.fetch()
            ci.consume_data()
            self.assertEqual("", log_file.getvalue())

        mockobj.assert_has_calls([
            mock.call(outpath, script, 0o700),
            mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600)])
Exemple #44
0
    def CloseItem(self, msgid=None, uid=None):
        if uid:
            msgid = self.UidToMsgId(uid)

        if not isinstance(msgid, list):
            msgid = [msgid]

        for ID in msgid:
            f =  MIMEBase('MsgItem', 'option')
            f['Subject']       = Header('option', 'UTF-8')
            f['From']          = self.user
            f['To']            = self.user
            f['Reply-To']      = self.user
            f['In-Reply-To']   = ID
            f['X-Item-Status'] = 'close'
            encode_base64(f)

            msg = f.as_string()

            self.imap.append(self.folder, msg)
Exemple #45
0
def SendingMail(reciept, filename):
    import mimetypes
    import mysmtplib
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    
    #global value
    host = "smtp.gmail.com" # Gmail STMP 서버 주소.
    port = "587"
    htmlFileName = filename
    
    senderAddr = "*****@*****.**"     # 보내는 사람 email 주소.
    recipientAddr = str(reciept)   # 받는 사람 email 주소.
    
    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "Term Project"
    msg['From'] = senderAddr
    msg['To'] = recipientAddr
    
    # MIME 문서를 생성합니다.
    htmlFD = open(htmlFileName, 'rb')
    HtmlPart = MIMEText(htmlFD.read(), _charset = 'UTF-8' )
    htmlFD.close()
    
    # 만들었던 mime을 MIMEBase에 첨부 시킨다.
    msg.attach(HtmlPart)
    
    # 메일을 발송한다.
    s = mysmtplib.MySMTP(host,port)
    s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**","ghdlghdl11~")
    s.sendmail(senderAddr , [recipientAddr], msg.as_string())
    s.close()
Exemple #46
0
    def SendEmail(self):
        os.system('cls')
        #global value
        host = "smtp.gmail.com" # Gmail STMP 서버 주소.
        port = "587"
        htmlFileName = "foodrtrt.xml"

        senderAddr = "*****@*****.**"     # 보내는 사람 email 주소.
        recipientAddr = " "
        recipientAddr = str(input("메일 주소를 입력하세요 : "))

        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "스크립트 텀프로젝트 테스트 메일"
        msg['From'] = senderAddr
        msg['To'] = recipientAddr

        # MIME 문서를 생성합니다.
        htmlFD = open(htmlFileName, 'rb')
        HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
        htmlFD.close()

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(HtmlPart)
        print("\n")
        print("******메일을 보내는 중입니다******")
        print("\n")
        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host,port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login("*****@*****.**","roslal12")
        s.sendmail(senderAddr , [recipientAddr], msg.as_string())
        print("******메일 전송 완료******")
        s.close()
    def execute_with_blob(self, command, blob_content, filename, **params):
        """Execute an Automation operation with a blob input

        Beware that the whole content is loaded in memory when calling this.
        """
        self._check_params(command, params)
        url = self.automation_url.encode('ascii') + command

        # Create data by hand :(
        boundary = "====Part=%s=%s===" % (str(time.time()).replace('.', '='),
                                          random.randint(0, 1000000000))
        headers = {
            "Accept": "application/json+nxentity, */*",
            "Content-Type": ('multipart/related;boundary="%s";'
                             'type="application/json+nxrequest";'
                             'start="request"')
            % boundary,
        }
        headers.update(self._get_common_headers())

        container = MIMEMultipart("related",
                type="application/json+nxrequest",
                start="request")

        d = {'params': params}
        json_data = json.dumps(d)
        json_part = MIMEBase("application", "json+nxrequest")
        json_part.add_header("Content-ID", "request")
        json_part.set_payload(json_data)
        container.attach(json_part)

        ctype, _ = mimetypes.guess_type(filename)
        if ctype:
            maintype, subtype = ctype.split('/', 1)
        else:
            maintype, subtype = "application", "octet-stream"
        blob_part = MIMEBase(maintype, subtype)
        blob_part.add_header("Content-ID", "input")
        blob_part.add_header("Content-Transfer-Encoding", "binary")

        # Quote UTF-8 filenames even though JAX-RS does not seem to be able
        # to retrieve them as per: https://tools.ietf.org/html/rfc5987
        filename = safe_filename(filename)
        quoted_filename = urllib2.quote(filename.encode('utf-8'))
        content_disposition = ("attachment; filename*=UTF-8''%s"
                                % quoted_filename)
        blob_part.add_header("Content-Disposition", content_disposition)
        blob_part.set_payload(blob_content)
        container.attach(blob_part)

        data = (
            "--%s\r\n"
            "%s\r\n"
            "--%s\r\n"
            "%s\r\n"
            "--%s--"
        ) % (
            boundary,
            json_part.as_string(),
            boundary,
            blob_part.as_string(),
            boundary,
        )

        cookies = self._get_cookies()
        log.trace("Calling %s with headers %r and cookies %r for file %s",
            url, headers, cookies, filename)
        req = urllib2.Request(url, data, headers)
        try:
            resp = self.opener.open(req, timeout=self.blob_timeout)
        except Exception as e:
            self._log_details(e)
            raise

        return self._read_response(resp, url)
Exemple #48
0
#global value
host = "smtp.gmail.com" # Gmail STMP 서버 주소.
port = "587"
htmlFileName = "logo.html"

senderAddr = "*****@*****.**"     # 보내는 사람 email 주소.
recipientAddr = "*****@*****.**"   # 받는 사람 email 주소.

msg = MIMEBase("multipart", "alternative")
msg['Subject'] = "Test email in Python 3.0"
msg['From'] = senderAddr
msg['To'] = recipientAddr

# MIME 문서를 생성합니다.
htmlFD = open(htmlFileName, 'rb')
HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )
htmlFD.close()

# 만들었던 mime을 MIMEBase에 첨부 시킨다.
msg.attach(HtmlPart)

# 메일을 발송한다.
s = mysmtplib.MySMTP(host,port)
#s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
s.ehlo()
s.starttls()
s.ehlo()
s.login("본인계정","본인암호")
s.sendmail(senderAddr , [recipientAddr], msg.as_string())
s.close()
def SendMail():
    os.system('cls')

    print("\n")
    print("\t---------------")
    print("\t 전송정보 검색")
    print("\t---------------")
    print("\t1) 월별 검색 ")
    print("\t2) 일별 검색 ")
    print("\t3) 나가기 ")
    print("\t--------------- \n")

    sel = int(input("\t선택: "))

    if (sel == 3):
        return

    SearchPerformanceInfo(sel)

    root = Parse("Performance_Info.xml")

    f = open("data.txt", "w")

    for data in root.findall("row"):
        f.write(" ----------------------------------\n")
        f.write(" 일련번호 : " + data.findtext("PSCHE_SEQ") + "\n")
        f.write(" 공연자명 : " + data.findtext("NAME") + "\n")
        f.write(" 공연내용 : " + data.findtext("CMT") + "\n")
        f.write(" 공연장소 : " + data.findtext("PLACE") + "\n")
        f.write(" 시작시간 : " + data.findtext("SDATE") + "\n")
        f.write(" 종료시간 : " + data.findtext("EDATE") + "\n")
        f.write(" ----------------------------------\n\n")

    f.close()

    # smtp 서버 주소
    smtp_host = "smtp.test.com"

    # gmail STMP 서버 주소
    host = "smtp.gmail.com"
    port = "587"
    
    file_name = "data.txt"

    send_addr = "*****@*****.**"  
    recv_addr = input("\t받는 사람 : ")

    print("\n\t이메일 전송 준비 중...")
    
    msg = MIMEBase("multipart", "alternative")
    msg['Subject'] = "Performance Information"
    msg['From'] = send_addr
    msg['To'] = recv_addr
    
    # MIME 문서를 생성
    html_fd = open(file_name, "rb")

    message = html_fd.read()

    html_part = MIMEText(message, 'html', _charset = 'UTF-8')
    html_fd.close()
    
    # MIME를 MIMEBase에 첨부
    msg.attach(html_part)

    print("\t이메일 전송 중...")
    
    # 이메일 발송
    s = mysmtplib.MySMTP(host, port)
    #s.set_debuglevel(1)        
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login("*****@*****.**", "ekdlfprxm930")
    s.sendmail(send_addr, [recv_addr], msg.as_string())
    s.close()
Exemple #50
0
    def send(self):
        import http.client
        import mysmtplib
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText
        from xml.etree import ElementTree

        #global value
        host = "smtp.gmail.com" # Gmail STMP 서버 주소.
        port = "587"
        htmlFileName = "logo.html"

        #get data from e-mail gui
        number = self.input_email_number.toPlainText()     # 객체번호
        sender = self.input_email_sender.toPlainText()     # 보내는 사람 email 주소.
        password = self.input_email_password.toPlainText() # 패스워드.
        target = self.input_email_target.toPlainText()     # 받는 사람 email 주소.
        
        #get xml from object number
        key = "VZwF3B6OId9MZtOCoLO8pS5FCjIXGQj3MYkPenIahW0vcGzgC%2Bb8rJHcYoDRPk%2Fc9dsbldkOhJi0mBewN4UBMg%3D%3D"
        conn = http.client.HTTPConnection("data.ekape.or.kr")
        conn.request("GET", "/openapi-data/service/user/animalTrace/traceNoSearch?ServiceKey=" + key + "&traceNo=" + number) #서버에 GET 요청 

        req = conn.getresponse()    #openAPI 서버에서 보내온 요청을 받아옴
        cLen = bytearray(req.getheader("Content-Length"), 'utf-8')    #가져온 데이터 길이

        if int(req.status) == 200 :
            strXml = (req.read().decode('utf-8'))    #요청이 성공이면 book 정보 추출
            strList = ""
            tree = ElementTree.fromstring(strXml)
            
            itemElements = tree.getiterator("item")
            for item in itemElements:
                if (item.find("infoType")).text == "1" :
                    birthYmd = item.find("birthYmd")    #birthYmd 검색
                    cattleNo = item.find("cattleNo")    #cattleNo 검색
                    lsTypeNm = item.find("lsTypeNm")    #lsTypeNm 검색
                    sexNm = item.find("sexNm")          #sexNm 검색
        
                    strList += (str(birthYmd.text) + "\t" + str(cattleNo.text) + "\t" + str(lsTypeNm.text) + "\t" + str(sexNm.text) + "\n")
                
                if (item.find("infoType")).text == "2" :
                    farmAddr = item.find("farmAddr")    		#birthYmd 검색
                    farmerNm = item.find("farmerNm") 		#cattleNo 검색
                    regType = item.find("regType")
                    regYmd = item.find("regYmd")
        
                    strList += (str(farmAddr.text) + "\t" + str(farmerNm.text) + "\t" + str(regType.text) + "\t"+ str(regYmd.text) + "\n")
                
                if (item.find("infoType")).text == "3" :
                    butcheryYmd = item.find("butcheryYmd")              #butcheryYmd 검색
                    butcheryPlaceNm = item.find("butcheryPlaceNm")      #butcheryPlaceNm 검색
                    inspectPassYn = item.find("inspectPassYn")          #inspectPassYn 검색
                    
                    strList += (str(butcheryYmd.text) + "\t" + str(butcheryPlaceNm.text) + "\t" + str(inspectPassYn.text) + "\t")
                    
                if (item.find("infoType")).text == "4" :
                    processPlaceNm = item.find("processPlaceNm")         #processPlaceNm 검색
                    
                    strList += (str(processPlaceNm.text) + "\n")
        
        
        msg = MIMEBase("multipart", "alternative")
        msg['Subject'] = "Animal Husbandry Management xml - " + number
        msg['From'] = sender
        msg['To'] = target

        # MIME 문서를 생성합니다.
        htmlPart = MIMEText(str(strList), 'html', _charset = 'UTF-8')

        # 만들었던 mime을 MIMEBase에 첨부 시킨다.
        msg.attach(htmlPart)

        # 메일을 발송한다.
        s = mysmtplib.MySMTP(host,port)
        #s.set_debuglevel(1)        # 디버깅이 필요할 경우 주석을 푼다.
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(sender, password)
        s.sendmail(sender, [target], msg.as_string())
        s.close()
Exemple #51
0
textF.close()



# attach html,image

#msg.attach(imagePart)
msg.attach(textPart)



# mail send

s=smtplib.SMTP(host,port)

s.set_debuglevel(1) #debuging

s.ehlo()

s.starttls()

s.ehlo()

s.login(sender,passward)

s.sendmail(sender,[recipient],msg.as_string())

s.close()


Exemple #52
0
def sendArf(item, spam=False):
    global reportSender
    global mailSmtp
    global reportEmailCc
    global reportEmailSpamCc

    msg = MIMEBase('multipart','report')
    msg.set_param('report-type','feedback-report',requote=False)

    msg["To"] = str(item['emailAbuse'])
    msg["From"] = reportSender
    msg["Subject"] = "Abuse report for: "+str(item['subject'])

    if spam:
        text = "This is an email in the abuse report format (ARF) for an email message coming via these \r\n"
        text = text+"IPs "+str(item['sourceIp'])+" on "+str(item['arrivalDate'])+".\r\n"
        text = text+"This report indicates that the attached email was not wanted by the recipient.\r\n"
        text = text+"This report may indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text+"This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text+"The zip attachment is the complete email encrypted with the password "+str(arfPassword)+"\r\n";
        text = text+"For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n";
    else:
        text = "This is an email in the abuse report format (ARF) for an email message received from \r\n"
        text = text+"IP "+str(item['sourceIp'])+" "+str(item['sourceDomain'])+" on "+str(item['arrivalDate'])+" UTC.\r\n"
        text = text+"This report likely indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text+"The attached email was selected amongst emails that failed DMARC,\r\n"
        text = text+"therefore it indicates that the author tried to pass for someone else\r\n"
        text = text+"indicating fraud and not spam. The faster you fix or isolate the compromised machine, \r\n"
        text = text+"the better you protect your customers or members and the Internet at large.\r\n\r\n"
        text = text+"This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text+"The zip attachment is the complete email encrypted with the password "+str(arfPassword)+"\r\n";
        text = text+"For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n";

    msgtxt = MIMEText(text)
    msg.attach(msgtxt)

    msgreport = MIMEBase('message', "feedback-report")
    msgreport.set_charset("US-ASCII")
    
    if spam:
        text = "Feedback-Type: abuse\r\n"
    else:
        text = "Feedback-Type: fraud\r\n"
    text = text + "User-Agent: pyforensic/1.1\r\n"
    text = text + "Version: 1.0\r\n"
    if not spam:
        text = text + "Source-IP: "+str(item['sourceIp'])+"\r\n"
    else:
        ipList = item['sourceIp'].split(", ")
        for ip in ipList:
            text = text + "Source-IP: "+str(ip)+"\r\n"

    text = text + "Arrival-Date: "+str(item['arrivalDate'])+" UTC\r\n"

    text = text + "Attachment-Password: "******"\r\n"

    if 'urlList' in item:
        for uri in item['urlList']:
            o = urlparse.urlparse(uri)
            urlReport=True
            if o.hostname is not None:
                for domain in wldomain:
                    if o.hostname[-len(domain):]==domain:
                        urlReport=False
                if urlReport==True:
                    text = text + "Reported-Uri: "+str(uri)+"\r\n"

    msgreport.set_payload(text)
    msg.attach(msgreport)

    #msgrfc822 = MIMEBase('message', "rfc822")
    msgrfc822 = MIMEBase('text', "rfc822-headers")
    msgrfc822.add_header('Content-Disposition','inline')
    parts=re.split(r'\r\n\r\n|\n\n',item['content'])
    rfc822headers=parts[0]
    #msgrfc822.set_payload(item['content'])
    msgrfc822.set_payload(rfc822headers)
    
    msg.attach(msgrfc822)

    #prepare the zip encrypted
    temp=tempfile.NamedTemporaryFile(prefix='mail',suffix='.eml',delete=False)
    tempname=temp.name
    temp.write(item['content'])
    temp.flush()
    ziptemp = tempfile.NamedTemporaryFile(prefix='mail',suffix='.zip',delete=True)
    ziptempname=ziptemp.name
    ziptemp.close()
    workdir = os.path.dirname(ziptempname)
    filenamezip = os.path.basename(ziptempname)
    filenameemail = os.path.basename(tempname)
    os.chdir(workdir)
    option = '-P%s' % arfPassword
    rc = subprocess.call(['zip', option] + [filenamezip, filenameemail])
    temp.close()

    
    ziptemp = open(ziptempname,"r")
    msgzip = MIMEBase('application', "zip")
    msgzip.set_payload(ziptemp.read())
    encoders.encode_base64(msgzip)
    msgzip.add_header('Content-Disposition', 'attachment', filename=filenamezip)
    ziptemp.close()

    msg.attach(msgzip)

    #delete created files
    os.remove(ziptempname)
    os.remove(tempname)


    #print "******************\r\n"
    #print msg.as_string()
    #print "******************\r\n"

    s = smtplib.SMTP(mailSmtp)
    # send to IP owners first
    if msg["To"] != "":
        toList = msg["To"].split(",")
        s.sendmail(msg["From"], toList, msg.as_string())
    # send a copy
    reportEmail=reportEmailCc
    if spam:
        reportEmail=reportEmailSpamCc
    if reportEmail != "":
        toList = reportEmail.split(",")
        for emailAddress in toList:
            if msg.has_key("To"):
                msg.replace_header("To",str(emailAddress))
            else:
                msg["To"]=str(emailAddress)
            s.sendmail(msg["From"], emailAddress, msg.as_string())
            
    s.quit()
    def execute_with_blob(self, command, blob_content, filename, **params):
        self._check_params(command, None, params)

        container = MIMEMultipart("related",
                type="application/json+nxrequest",
                start="request")

        d = {'params': params}
        json_data = json.dumps(d)
        json_part = MIMEBase("application", "json+nxrequest")
        json_part.add_header("Content-ID", "request")
        json_part.set_payload(json_data)
        container.attach(json_part)

        ctype, encoding = mimetypes.guess_type(filename)
        if ctype:
            maintype, subtype = ctype.split('/', 1)
        else:
            maintype, subtype = "application", "octet-stream"
        blob_part = MIMEBase(maintype, subtype)
        blob_part.add_header("Content-ID", "input")
        blob_part.add_header("Content-Transfer-Encoding", "binary")

        # Quote UTF-8 filenames eventhough JAX-RS does not seem to be able
        # to retrieve them as per: https://tools.ietf.org/html/rfc5987
        quoted_filename = urllib.quote(filename.encode('utf-8'))
        content_disposition = ("attachment; filename*=UTF-8''%s"
                                % quoted_filename)
        blob_part.add_header("Content-Disposition", content_disposition)
        blob_part.set_payload(blob_content)
        container.attach(blob_part)

        # Create data by hand :(
        boundary = "====Part=%s=%s===" % (str(time.time()).replace('.', '='),
                                          random.randint(0, 1000000000))
        headers = {
            "Accept": "application/json+nxentity, */*",
            "Content-Type": ('multipart/related;boundary="%s";'
                             'type="application/json+nxrequest";'
                             'start="request"')
            % boundary,
        }
        headers.update(self._get_common_headers())

        # TODO: find a way to stream the parts without loading them all in
        # memory as a byte string

        # The code http://atlee.ca/software/poster/ might provide some
        # guidance to implement this although it cannot be reused directly
        # as we need tighter control on the headers of the multipart
        data = (
            "--%s\r\n"
            "%s\r\n"
            "--%s\r\n"
            "%s\r\n"
            "--%s--"
        ) % (
            boundary,
            json_part.as_string(),
            boundary,
            blob_part.as_string(),
            boundary,
        )
        url = self.automation_url.encode('ascii') + command
        log.trace("Calling '%s' for file '%s'", url, filename)
        req = urllib2.Request(url, data, headers)
        try:
            resp = self.opener.open(req, timeout=self.blob_timeout)
        except Exception as e:
            self._log_details(e)
            raise

        info = resp.info()
        s = resp.read()

        content_type = info.get('content-type', '')
        if content_type.startswith("application/json"):
            log.trace("Response for '%s' with json payload: %r", url, s)
            return json.loads(s) if s else None
        else:
            log.trace("Response for '%s' with content-type: %r", url,
                      content_type)
            return s
Exemple #54
0
class LOLDIC:
    def __init__(self):
        self.inputKey         = 0
        self.region           = "kr"
        self.riotApiKey       = "1cf626bc-7f5a-4236-8f5b-803ace8953af"
        self.response         = 0
        self.responseChampion = 0
        self.dict             = dict(
                                       summonerName  = "",
                                       summonerID    = "",
                                       summonerLevel = 0)
        self.maxIndex         = 600
        self.senderAddress    = ""
        self.senderPassword   = ""
        self.receiverAddress  = ""
    def sceneMenu(self):
        while 1:
            os.system("cls")
            print("♬ LOLDIC")
            print("♬ Menu")
            print("\t1. 소환사")
            print("\t2. 챔피언")
            print("\t3. 업데이트")
            print("\t4. 메일송신")
            print("\t9. 종료")
            self.inputKey = int(input("♬ Select : "))
            if 1 == self.inputKey:
                self.searchBySummonerName()
            elif 2 == self.inputKey:
                self.searchByChampionName()
            elif 3 == self.inputKey:
                self.updateData()
            elif 4 == self.inputKey:
                self.sendMail()
            elif 9 == self.inputKey:
                sys.exit()
            else:
                print("♬ System")
                print("\t잘못된 입력값입니다.")
            input("\t계속하려면 아무 키나 입력하십시오.")
    def searchBySummonerName(self):
        self.flagWhile = True
        os.system("cls")
        print("♬ LOLDIC/소환사")
        # 최종목표 서모너 레벨, 소속리그, 티어, 리그포인트        
        # 검색값 : summonerName
        self.dict['summonerName'] = str(input("♬ summonerName : "))
        # 리퀘스트 summoner-v1.4 summonerName
        self.response     = requests.get(("https://kr.api.pvp.net/api/lol/kr/v1.4/summoner/by-name/{0}?&api_key={1}").format(self.dict['summonerName'], self.riotApiKey))
        print(self.response)
        print(self.response.json())
        self.dict['summonerID']    = self.response.json()[self.dict['summonerName']]['id']
        self.dict['summonerLevel'] = self.response.json()[self.dict['summonerName']]['summonerLevel']
        while self.flagWhile:
            os.system("cls")
            print("♬ LOLDIC/소환사/"+self.dict['summonerName'])
            print("♬ SearchResult")
            print("\tsummonerName  : " + self.dict['summonerName'])
            print("\tsummonerID    : " + str(self.dict['summonerID']))
            print("\tsummonerLevel : " + str(self.dict['summonerLevel']))
            print("♬ Menu")
            print("\t1. 솔로랭크")
            print("\t2. 언랭크")
            print("\t3. 우르프")
            print("\t4. 현재게임")
            print("\t9. 뒤로")
            self.inputKey = int(input("♬ Select : "))
            if 9 == self.inputKey:
                self.flagWhile = False
            elif 1 == self.inputKey:
                # 리퀘스트 stats -v1.3 스탯
                os.system("cls")
                print("♬ LOLDIC/소환사/"+self.dict['summonerName']+"/솔로랭크")
                print("♬ SearchResult")
                self.response     = requests.get(("https://kr.api.pvp.net/api/lol/kr/v1.3/stats/by-summoner/{0}/summary?season=SEASON2016&api_key={1}").format(self.dict['summonerID'], self.riotApiKey))
                #print(self.response)
                #print(self.response.json())
                # 넘어오는 json값의 리스트 인덱스 순서가 유저ID마다 다르므로
                # 원하는 정보가 어느 인덱스 값에 있는지 알아내야 한다.
                for i in range(0, 8):
                    if "RankedSolo5x5" == self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']:                        
                        self.dict['playerStatSummaryType']     = self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']
                        self.dict['totalNeutralMinionsKilled'] = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalNeutralMinionsKilled'] 
                        self.dict['totalMinionKills']          = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalMinionKills'] 
                        self.dict['totalChampionKills']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalChampionKills'] 
                        self.dict['totalAssists']              = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalAssists'] 
                        self.dict['totalTurretsKilled']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalTurretsKilled'] 
                        self.dict['wins']                      = self.response.json()['playerStatSummaries'][i]['wins']
                        self.dict['losses']                    = self.response.json()['playerStatSummaries'][i]['losses']
                        print("\tplayerStatSummaryType     : "+str(self.dict['playerStatSummaryType']))
                        print("\ttotalNeutralMinionsKilled : "+str(self.dict['totalNeutralMinionsKilled']))
                        print("\ttotalMinionKills          : "+str(self.dict['totalMinionKills']))
                        print("\ttotalChampionKills        : "+str(self.dict['totalChampionKills']))
                        print("\ttotalAssists              : "+str(self.dict['totalAssists']))
                        print("\ttotalTurretsKilled        : "+str(self.dict['totalTurretsKilled']))
                        print("\twins                      : "+str(self.dict['wins']))
                        print("\tlosses                    : "+str(self.dict['losses']))
                print("♬ System")
                input("\t계속하려면 아무 키나 입력하십시오.")    
            elif 2 == self.inputKey:
                os.system("cls")
                print("♬ LOLDIC/소환사/"+self.dict['summonerName']+"/언랭크")
                print("♬ SearchResult")
                self.response     = requests.get(("https://kr.api.pvp.net/api/lol/kr/v1.3/stats/by-summoner/{0}/summary?season=SEASON2016&api_key={1}").format(self.dict['summonerID'], self.riotApiKey))
                #print(self.response)
                #print(self.response.json())
                # 넘어오는 json값의 리스트 인덱스 순서가 유저ID마다 다르므로
                # 원하는 정보가 어느 인덱스 값에 있는지 알아내야 한다.
                for i in range(0, 8):
                    if "Unranked" == self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']:                        
                        self.dict['playerStatSummaryType']     = self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']
                        self.dict['totalNeutralMinionsKilled'] = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalNeutralMinionsKilled'] 
                        self.dict['totalMinionKills']          = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalMinionKills'] 
                        self.dict['totalChampionKills']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalChampionKills'] 
                        self.dict['totalAssists']              = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalAssists'] 
                        self.dict['totalTurretsKilled']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalTurretsKilled'] 
                        self.dict['wins']                      = self.response.json()['playerStatSummaries'][i]['wins']
                        print("\tplayerStatSummaryType     : "+str(self.dict['playerStatSummaryType']))
                        print("\ttotalNeutralMinionsKilled : "+str(self.dict['totalNeutralMinionsKilled']))
                        print("\ttotalMinionKills          : "+str(self.dict['totalMinionKills']))
                        print("\ttotalChampionKills        : "+str(self.dict['totalChampionKills']))
                        print("\ttotalAssists              : "+str(self.dict['totalAssists']))
                        print("\ttotalTurretsKilled        : "+str(self.dict['totalTurretsKilled']))
                        print("\twins                      : "+str(self.dict['wins']))
                print("♬ System")
                input("\t계속하려면 아무 키나 입력하십시오.")               
            elif 3 == self.inputKey:
                os.system("cls")
                print("♬ LOLDIC/소환사/"+self.dict['summonerName']+"/우르프")
                print("♬ SearchResult")
                self.response     = requests.get(("https://kr.api.pvp.net/api/lol/kr/v1.3/stats/by-summoner/{0}/summary?season=SEASON2016&api_key={1}").format(self.dict['summonerID'], self.riotApiKey))
                #print(self.response)
                #print(self.response.json())
                # 넘어오는 json값의 리스트 인덱스 순서가 유저ID마다 다르므로
                # 원하는 정보가 어느 인덱스 값에 있는지 알아내야 한다.
                for i in range(0, 8):
                    if "URF" == self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']:                        
                        self.dict['playerStatSummaryType']     = self.response.json()['playerStatSummaries'][i]['playerStatSummaryType']
                        self.dict['totalNeutralMinionsKilled'] = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalNeutralMinionsKilled'] 
                        self.dict['totalMinionKills']          = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalMinionKills'] 
                        self.dict['totalChampionKills']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalChampionKills'] 
                        self.dict['totalAssists']              = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalAssists'] 
                        self.dict['totalTurretsKilled']        = self.response.json()['playerStatSummaries'][i]['aggregatedStats']['totalTurretsKilled'] 
                        self.dict['wins']                      = self.response.json()['playerStatSummaries'][i]['wins']
                        print("\tplayerStatSummaryType     : "+str(self.dict['playerStatSummaryType']))
                        print("\ttotalNeutralMinionsKilled : "+str(self.dict['totalNeutralMinionsKilled']))
                        print("\ttotalMinionKills          : "+str(self.dict['totalMinionKills']))
                        print("\ttotalChampionKills        : "+str(self.dict['totalChampionKills']))
                        print("\ttotalAssists              : "+str(self.dict['totalAssists']))
                        print("\ttotalTurretsKilled        : "+str(self.dict['totalTurretsKilled']))
                        print("\twins                      : "+str(self.dict['wins']))
                print("♬ System")
                input("\t계속하려면 아무 키나 입력하십시오.")       
            elif 4 == self.inputKey:
                # current-game-v1.0 API 사용
                os.system("cls")
                print("♬ LOLDIC/소환사/"+self.dict['summonerName']+"/현재게임")
                print("♬ SearchResult")

                self.response     = requests.get(("https://kr.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/KR/{0}?season=SEASON2016&api_key={1}").format(self.dict['summonerID'], self.riotApiKey))
                if str(self.response) != "<Response [200]>":
                    print("\t" + str(self.response))
                    print("♬ System")
                    print("\t진행 중인 게임을 찾을 수 없습니다.")
                    input("\t계속하려면 아무 키나 입력하십시오.")      
                elif str(self.response) == "<Response [200]>":
                    #print(self.response)
                    print(self.response.json())
                    # 넘어오는 json값의 리스트 인덱스 순서가 유저ID마다 다르므로
                    # 원하는 정보가 어느 인덱스 값에 있는지 알아내야 한다.
                    self.dict['gameLength']       = self.response.json()['gameLength']
                    self.dict['gameMode']         = self.response.json()['gameMode']
                    self.dict['gameType']         = self.response.json()['gameType']
                    self.dict['gameId']           = self.response.json()['gameId']
                    print("\tgameLength       : "+str(self.dict['gameLength']))
                    print("\tgameMode         : "+str(self.dict['gameMode']))
                    print("\tgameType         : "+str(self.dict['gameType']))
                    print("\tgameId           : "+str(self.dict['gameId'])) 
                    print("")
                    # 플레이어
                    print("♬ SearchResult/블루팀")
                    for i in range(0, 10):
                        if self.response.json()['participants'][i]['teamId'] == 100:
                            print("\tparticipants" + str(i) + " : "+str(self.response.json()['participants'][i]['summonerName']))
                            # 플레이 중인 챔피언 출력
                            self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.response.json()['participants'][i]['championId'], self.riotApiKey))
                            print("\t                "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                            
                    print("")
                    print("♬ SearchResult/퍼플팀")
                    for i in range(0, 10):
                        if self.response.json()['participants'][i]['teamId'] == 200:
                            print("\tparticipants" + str(i) + " : "+str(self.response.json()['participants'][i]['summonerName']))
                            # 플레이 중인 챔피언 출력
                            self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.response.json()['participants'][i]['championId'], self.riotApiKey))
                            print("\t                "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    # 밴 챔프
                    self.dict['bannedChampions0'] = self.response.json()['bannedChampions'][0]['championId']
                    self.dict['bannedChampions1'] = self.response.json()['bannedChampions'][1]['championId']
                    self.dict['bannedChampions2'] = self.response.json()['bannedChampions'][2]['championId']
                    self.dict['bannedChampions3'] = self.response.json()['bannedChampions'][3]['championId']
                    self.dict['bannedChampions4'] = self.response.json()['bannedChampions'][4]['championId']
                    self.dict['bannedChampions5'] = self.response.json()['bannedChampions'][5]['championId']

                    print("")
                    print("♬ SearchResult/밴카드")
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions0'], self.riotApiKey))
                    print("\tbannedChampions0 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions1'], self.riotApiKey))
                    print("\tbannedChampions1 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions2'], self.riotApiKey))
                    print("\tbannedChampions2 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions3'], self.riotApiKey))
                    print("\tbannedChampions3 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions4'], self.riotApiKey))
                    print("\tbannedChampions4 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?season=SEASON2016&api_key={1}").format(self.dict['bannedChampions5'], self.riotApiKey))
                    print("\tbannedChampions5 : "+str(self.responseChampion.json()['title']) + " " + str(self.responseChampion.json()['name']) + " " + str(self.responseChampion.json()['key']))
                    print("♬ System")
                    input("\t계속하려면 아무 키나 입력하십시오.")
            else:
                print("♬ System")
                print("\t잘못된 입력값입니다.")
    def searchByChampionName(self):
        os.system("cls")
        print("♬ LOLDIC/챔피언")
        self.championName = input("♬ What the ? : ")
        # json값을 미리 파일로 저장해서 불러오려고 했는데 안되서
        # 그냥 코드상으로 넣었다.
        self.jsonString = '{ "maxIndex" : 600, "champion" : [{"id" : 1, "key" : "Annie"},{"id" : 2, "key" : "Olaf"},{"id" : 3, "key" : "Galio"},{"id" : 4, "key" : "TwistedFate"},{"id" : 5, "key" : "XinZhao"},{"id" : 6, "key" : "Urgot"},{"id" : 7, "key" : "Leblanc"},{"id" : 8, "key" : "Vladimir"},{"id" : 9, "key" : "FiddleSticks"},{"id" : 10, "key" : "Kayle"},{"id" : 11, "key" : "MasterYi"},{"id" : 12, "key" : "Alistar"}, {"id" : 13, "key" : "Ryze"},{"id" : 14, "key" : "Sion"},{"id" : 15, "key" : "Sivir"}, {"id" : 16, "key" : "Soraka"},{"id" : 17, "key" : "Teemo"},{"id" : 18, "key" : "Tristana"},{"id" : 19, "key" : "Warwick"},{"id" : 20, "key" : "Nunu"},{"id" : 21, "key" : "MissFortune"},{"id" : 22, "key" : "Ashe"},{"id" : 23, "key" : "Tryndamere"},{"id" : 24, "key" : "Jax"},{"id" : 25, "key" : "Morgana"},{"id" : 26, "key" : "Zilean"},{"id" : 27, "key" : "Singed"},{"id" : 28, "key" : "Evelynn"},{"id" : 29, "key" : "Twitch"},{"id" : 30, "key" : "Karthus"},{"id" : 31, "key" : "Chogath"},{"id" : 32, "key" : "Amumu"},{"id" : 33, "key" : "Rammus"},{"id" : 34, "key" : "Anivia"},{"id" : 35, "key" : "Shaco"},{"id" : 36, "key" : "DrMundo"},{"id" : 37, "key" : "Sona"},{"id" : 38, "key" : "Kassadin"},{"id" : 39, "key" : "Irelia"},{"id" : 40, "key" : "Janna"},{"id" : 41, "key" : "Gangplank"},{"id" : 42, "key" : "Corki"},{"id" : 43, "key" : "Karma"},{"id" : 44, "key" : "Taric"},{"id" : 45, "key" : "Veigar"},{"id" : 48, "key" : "Trundle"},{"id" : 50, "key" : "Swain"},{"id" : 51, "key" : "Caitlyn"},{"id" : 53, "key" : "Blitzcrank"},{"id" : 54, "key" : "Malphite"},{"id" : 55, "key" : "Katarina"},{"id" : 56, "key" : "Nocturne"},{"id" : 57, "key" : "Maokai"},{"id" : 58, "key" : "Renekton"},{"id" : 59, "key" : "JarvanIV"},{"id" : 60, "key" : "Elise"},{"id" : 61, "key" : "Orianna"},{"id" : 62, "key" : "MonkeyKing"},{"id" : 63, "key" : "Brand"},{"id" : 64, "key" : "LeeSin"},{"id" : 67, "key" : "Vayne"},{"id" : 68, "key" : "Rumble"},{"id" : 69, "key" : "Cassiopeia"},{"id" : 72, "key" : "Skarner"},{"id" : 74, "key" : "Heimerdinger"},{"id" : 75, "key" : "Nasus"},{"id" : 76, "key" : "Nidalee"},{"id" : 77, "key" : "Udyr"},{"id" : 78, "key" : "Poppy"},{"id" : 79, "key" : "Gragas"},{"id" : 80, "key" : "Pantheon"},{"id" : 81, "key" : "Ezreal"},{"id" : 82, "key" : "Mordekaiser"},{"id" : 83, "key" : "Yorick"},{"id" : 84, "key" : "Akali"},{"id" : 85, "key" : "Kennen"},{"id" : 86, "key" : "Garen"},{"id" : 89, "key" : "Leona"},{"id" : 90, "key" : "Malzahar"},{"id" : 91, "key" : "Talon"},{"id" : 92, "key" : "Riven"},{"id" : 96, "key" : "KogMaw"},{"id" : 98, "key" : "Shen"},{"id" : 99, "key" : "Lux"},{"id" : 101, "key" : "Xerath"},{"id" : 102, "key" : "Shyvana"},{"id" : 103, "key" : "Ahri"},{"id" : 104, "key" : "Graves"},{"id" : 105, "key" : "Fizz"},{"id" : 106, "key" : "Volibear"},{"id" : 107, "key" : "Rengar"},{"id" : 110, "key" : "Varus"},{"id" : 111, "key" : "Nautilus"},{"id" : 112, "key" : "Viktor"},{"id" : 113, "key" : "Sejuani"},{"id" : 114, "key" : "Fiora"},{"id" : 115, "key" : "Ziggs"},{"id" : 117, "key" : "Lulu"},{"id" : 119, "key" : "Draven"},{"id" : 120, "key" : "Hecarim"},{"id" : 121, "key" : "Khazix"},{"id" : 122, "key" : "Darius"},{"id" : 126, "key" : "Jayce"},{"id" : 127, "key" : "Lissandra"},{"id" : 131, "key" : "Diana"},{"id" : 133, "key" : "Quinn"},{"id" : 134, "key" : "Syndra"},{"id" : 136, "key" : "AurelionSol"},{"id" : 143, "key" : "Zyra"},{"id" : 150, "key" : "Gnar"},{"id" : 154, "key" : "Zac"},{"id" : 157, "key" : "Yasuo"},{"id" : 161, "key" : "Velkoz"},{"id" : 163, "key" : "Taliyah"},{"id" : 201, "key" : "Braum"},{"id" : 202, "key" : "Jhin"},{"id" : 203, "key" : "Kindred"},{"id" : 222, "key" : "Jinx"},{"id" : 223, "key" : "TahmKench"},{"id" : 236, "key" : "Lucian"},{"id" : 238, "key" : "Zed"},{"id" : 245, "key" : "Ekko"},{"id" : 254, "key" : "Vi"},{"id" : 266, "key" : "Aatrox"},{"id" : 267, "key" : "Nami"},{"id" : 268, "key" : "Azir"},{"id" : 412, "key" : "Thresh"},{"id" : 420, "key" : "Illaoi"},{"id" : 421, "key" : "RekSai"},{"id" : 429, "key" : "Kalista"},{"id" : 432, "key" : "Bard"}] }'
        self.parsedJson = json.loads(self.jsonString)
        # 본래는 json의 리스트 사이즈를 알아내야 하지만 파이썬 초심자라는 입장상
        # 시간을 아끼기 위해 현재 리스트 사이즈를 임의로 세어 입력했다.
        print("♬ SearchResult")
        for i in range(0, 131):
            # 현재 영문 이름으로밖에 검색이 안된다.
            # 소문자로 변경해 비교한다.
            if self.championName.lower() == str(self.parsedJson['champion'][i]['key']).lower():
                print("\tindexId["+ str(self.parsedJson['champion'][i]['id']) + "]          : " + self.parsedJson['champion'][i]['key'])
                print("")
                self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?champData=stats&api_key={1}").format(self.parsedJson['champion'][i]['id'], self.riotApiKey))
                print("\thp                   : "+str(self.responseChampion.json()['stats']['hp']))
                print("\thpperlevel           : "+str(self.responseChampion.json()['stats']['hpperlevel']))
                print("\thpregen              : "+str(self.responseChampion.json()['stats']['hpregen']))
                print("\thpregenperlevel      : "+str(self.responseChampion.json()['stats']['hpregenperlevel']))
                print("")
                print("\tmp                   : "+str(self.responseChampion.json()['stats']['mp']))
                print("\tmpperlevel           : "+str(self.responseChampion.json()['stats']['mpperlevel']))
                print("\tmpregen              : "+str(self.responseChampion.json()['stats']['mpregen']))
                print("\tmpregenperlevel      : "+str(self.responseChampion.json()['stats']['mpregenperlevel']))
                print("")
                print("\tmovespeed            : "+str(self.responseChampion.json()['stats']['movespeed']))
                print("")
                print("\tattackrange          : "+str(self.responseChampion.json()['stats']['attackrange']))
                print("\tattackdamage         : "+str(self.responseChampion.json()['stats']['attackdamage']))
                print("\tattackdamageperlevel : "+str(self.responseChampion.json()['stats']['attackdamageperlevel']))
                print("\tattackspeedoffset    : "+str(self.responseChampion.json()['stats']['attackspeedoffset']))
                print("\tattackspeedperlevel  : "+str(self.responseChampion.json()['stats']['attackspeedperlevel']))
                print("")
                print("\tarmor                : "+str(self.responseChampion.json()['stats']['armor']))
                print("\tarmorperlevel        : "+str(self.responseChampion.json()['stats']['armorperlevel']))
                print("")
                print("\tspellblock           : "+str(self.responseChampion.json()['stats']['spellblock']))
                print("\tspellblockperlevel   : "+str(self.responseChampion.json()['stats']['spellblockperlevel']))
                print("")
                print("\tcrit                 : "+str(self.responseChampion.json()['stats']['crit']))
                print("\tcritperlevel         : "+str(self.responseChampion.json()['stats']['critperlevel']))
        print("♬ System")
    def updateData(self):
        os.system("cls")
        print("♬ LOLDIC/업데이트")
        print("♬ System")
        print("\t챔피언 목록을 갱신합니다.")
        print("\tApiKey를 무료로 발급받았기 때문에 무지하게 오래 걸릴 것입니다.")
        print("\t업데이트에 소요되는 시간은 인덱스 하나당 약 1초의 시간이 소요됩니다.")
        

        self.target = open('champion.txt', 'w')

        self.target.write("{ 'maxIndex' : " + str(self.maxIndex) + ", 'champion' : [\n")
        for i in range(0, self.maxIndex):
            self.responseChampion = requests.get(("https://global.api.pvp.net/api/lol/static-data/kr/v1.2/champion/{0}?api_key={1}").format(i, self.riotApiKey))
            if str(self.responseChampion) != "<Response [200]>":
                print(self.responseChampion)
            if str(self.responseChampion) == "<Response [200]>":
                #print(str(self.responseChampion.json()['id'])+" "+self.responseChampion.json()['title']+" "+self.responseChampion.json()['name']+" "+self.responseChampion.json()['key'])
                print(self.responseChampion.json())
                if i < self.maxIndex-1:                
                    self.target.write('{\"id\" : ' + str(self.responseChampion.json()['id']) + ', \"key\" : \"' + str(self.responseChampion.json()['key'])+"\"},\n")
                if i == self.maxIndex-1:                
                    self.target.write('{\"id\" : ' + str(self.responseChampion.json()['id']) + ', \"key\" : \"' + str(self.responseChampion.json()['key'])+"\"}\n")
        self.target.write("] }")
        self.target.close()
    def sendMail(self):
        os.system("cls")
        print("♬ LOLDIC/메일송신")
        print("♬ System")
        print("\t메일을 송신합니다.")
        self.senderAddress   = input("♬ 송신자 g-Mail   : ")
        self.senderPassword  = input("♬ 송신자 password : "******"♬ 수신자 e-Mail   : ")
        self.host = "smtp.gmail.com"
        self.port = "587"
        
        self.msg = MIMEBase("multipart", "alternative")
        self.msg['Subject'] = "라이엇 게임즈 - 문의주신 내용에 대한 답변입니다."
        self.msg['From']    = self.senderAddress
        self.msg['To']      = self.receiverAddress

        #MIME 문서 생성
        self.htmlFileName = "riotGames.html"
        self.htmlFD = open(self.htmlFileName, 'rb')
        self.htmlPart = MIMEText(self.htmlFD.read(), 'html', _charset = 'UTF-8')
        self.htmlFD.close()
        
        # MIMEBase에 첨부
        self.msg.attach(self.htmlPart)

        # 송신
        self.s = smtplib.SMTP(self.host, self.port)
        self.s.ehlo()
        self.s.starttls()
        self.s.ehlo()
        self.s.login(self.senderAddress, self.senderPassword)
        self.s.sendmail(self.senderAddress, [self.receiverAddress], self.msg.as_string())
        print("♬ System")
Exemple #55
0
    def attach_blob(self, ref, blob, filename, **params):
        container = MIMEMultipart("related",
                type="application/json+nxrequest",
                start="request")

        params['document'] = ref
        d = {'params': params}
        json_data = json.dumps(d)
        json_part = MIMEBase("application", "json+nxrequest")
        json_part.add_header("Content-ID", "request")
        json_part.set_payload(json_data)
        container.attach(json_part)

        ctype, encoding = mimetypes.guess_type(filename)
        if ctype:
            maintype, subtype = ctype.split('/', 1)
        else:
            maintype, subtype = "application", "binary"
        blob_part = MIMEBase(maintype, subtype)
        blob_part.add_header("Content-ID", "input")
        blob_part.add_header("Content-Transfer-Encoding", "binary")
        ascii_filename = filename.encode('ascii', 'ignore')
        #content_disposition = "attachment; filename=" + ascii_filename
        #quoted_filename = urllib.quote(filename.encode('utf-8'))
        #content_disposition += "; filename filename*=UTF-8''" \
        #    + quoted_filename
        #print content_disposition
        #blob_part.add_header("Content-Disposition:", content_disposition)

        # XXX: Use ASCCI safe version of the filename for now
        blob_part.add_header('Content-Disposition', 'attachment',
                             filename=ascii_filename)

        blob_part.set_payload(blob)
        container.attach(blob_part)

        # Create data by hand :(
        boundary = "====Part=%s=%s===" % (str(time.time()).replace('.', '='),
                                          random.randint(0, 1000000000))
        headers = {
            "Accept": "application/json+nxentity, */*",
            "Authorization": self.auth,
            "Content-Type": ('multipart/related;boundary="%s";'
                             'type="application/json+nxrequest";'
                             'start="request"')
            % boundary,
        }
        data = (
            "--%s\r\n"
            "%s\r\n"
            "--%s\r\n"
            "%s\r\n"
            "--%s--"
        ) % (
            boundary,
            json_part.as_string(),
            boundary,
            blob_part.as_string(),
            boundary,
        )
        url = self.automation_url.encode('ascii') + "Blob.Attach"
        log.trace("Calling '%s' for file '%s'", url, filename)
        req = urllib2.Request(url, data, headers)
        try:
            resp = self.opener.open(req)
        except Exception as e:
            self._log_details(e)
            raise
        s = resp.read()
        return s