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("메일 전송이 실패하였습니다.")
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 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()
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()
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()
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()
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 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()
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()
def mailsend(): email_user = '******' email_pass = '******' from_email = 'from_email' to_email = 'to_email' smtp_ssl_host = 'smtp.gmail.com' # smtp.mail.yahoo.com smtp_ssl_port = 465 s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port) s.login(email_user, email_pass) #msg = MIMEMultipart() msg = MIMEBase('multipart','mixed') msg['Subject'] = 'I have a picture' msg['From'] = from_email msg['To'] = to_email txt = MIMEText('백업 파일','plain','utf-8') msg.attach(txt) path = r'D:\dbbackup\1234.sql' 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) s.send_message(msg) s.quit() print("complete....")
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 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()
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
def full_format_to_message_object(parts: Union[dict, list], message: MIMEBase = None) -> MIMEBase: if not message: # This is the root part maintype, subtype = parts["mimeType"].split("/", 1) message = MIMEBase(maintype, subtype) for header in parts["headers"]: message[header["name"]] = header["value"] if message.get_content_maintype() == "multipart": full_format_to_message_object(parts["parts"], message) else: message.set_payload(parts["body"].get("data")) else: for part in parts: if part["mimeType"].split("/")[0] == "multipart": message_part = MIMEMultipart("mixed") full_format_to_message_object(part["parts"], message_part) message.attach(message_part) else: try: maintype, subtype = part["mimeType"].split("/", 1) except ValueError: # There's no valid mimetype, I saw the python parser set the mimetype to text/plain # when it did not understand the mimetype. maintype, subtype = "text", "plain" message_part = MIMEBase(maintype, subtype) for header in part["headers"]: message_part[header["name"]] = header["value"] # Dispite the Content-Transfer-Encoding, it seems like everything is encoded # in b64 data = base64.urlsafe_b64decode(part["body"].get("data", "")).decode() message_part.set_payload(data) message.attach(message_part) return message
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("메일을 전송하였습니다.")
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()
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 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()
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
def send_email(to_email, subject, plaintext, html=None, bounced_email: Optional[Message] = None): if NOT_SEND_EMAIL: LOG.d( "send email with subject %s to %s, plaintext: %s", subject, to_email, plaintext, ) return LOG.d("send email to %s, subject %s", to_email, subject) if POSTFIX_SUBMISSION_TLS: smtp = SMTP(POSTFIX_SERVER, 587) smtp.starttls() else: smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25) if bounced_email: msg = MIMEMultipart("mixed") # add email main body body = MIMEMultipart("alternative") body.attach(MIMEText(plaintext, "text")) if html: body.attach(MIMEText(html, "html")) msg.attach(body) # add attachment rfcmessage = MIMEBase("message", "rfc822") rfcmessage.attach(bounced_email) msg.attach(rfcmessage) else: msg = MIMEMultipart("alternative") msg.attach(MIMEText(plaintext, "text")) if html: msg.attach(MIMEText(html, "html")) msg["Subject"] = subject msg["From"] = f"{SUPPORT_NAME} <{SUPPORT_EMAIL}>" msg["To"] = to_email msg_id_header = make_msgid() msg["Message-ID"] = msg_id_header date_header = formatdate() msg["Date"] = date_header # add DKIM email_domain = SUPPORT_EMAIL[SUPPORT_EMAIL.find("@") + 1:] add_dkim_signature(msg, email_domain) msg_raw = msg.as_bytes() smtp.sendmail(SUPPORT_EMAIL, to_email, msg_raw)
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_attachments(self): text_content = "* Item one\n* Item two\n* Item three" self.message.attach(filename="test.txt", content=text_content, mimetype="text/plain") # Should guess mimetype if not provided... png_content = b"PNG\xb4 pretend this is the contents of a png file" self.message.attach(filename="test.png", content=png_content) # Should work with a MIMEBase object... pdf_content = b"PDF\xb4 pretend this is valid pdf data" mimeattachment = MIMEBase('application', 'pdf') mimeattachment.set_payload(pdf_content) mimeattachment[ "Content-Disposition"] = 'attachment; filename="custom filename"' # Mailgun requires filename self.message.attach(mimeattachment) # And also with an message/rfc822 attachment forwarded_email_content = sample_email_content() forwarded_email = message_from_bytes(forwarded_email_content) rfcmessage = MIMEBase("message", "rfc822") rfcmessage.add_header( "Content-Disposition", "attachment", filename="forwarded message") # Mailgun requires filename rfcmessage.attach(forwarded_email) self.message.attach(rfcmessage) self.message.send() files = self.get_api_call_files() attachments = [ value for (field, value) in files if field == 'attachment' ] self.assertEqual(len(attachments), 4) self.assertEqual(attachments[0], ('test.txt', text_content, 'text/plain')) self.assertEqual(attachments[1], ('test.png', png_content, 'image/png')) # type inferred from filename self.assertEqual(attachments[2], ("custom filename", pdf_content, 'application/pdf')) # Email messages can get a bit changed with respect to whitespace characters # in headers, without breaking the message, so we tolerate that: self.assertEqual(attachments[3][0], "forwarded message") self.assertEqualIgnoringHeaderFolding( attachments[3][1], b'Content-Type: message/rfc822\nMIME-Version: 1.0\n' + b'Content-Disposition: attachment; filename="forwarded message"\n' + b'\n' + forwarded_email_content) self.assertEqual(attachments[3][2], 'message/rfc822') # Make sure the image attachment is not treated as embedded: inlines = [value for (field, value) in files if field == 'inline'] self.assertEqual(len(inlines), 0)
def get_mime_payload(msg): if not msg.is_multipart(): mimemail = MIMEBase(msg.get_content_maintype(),msg.get_content_subtype(),charset=msg.get_content_charset()) mimemail.set_payload(msg.get_payload()) if msg.has_key('Content-Transfer-Encoding'): mimemail['Content-Transfer-Encoding'] = msg['Content-Transfer-Encoding'] else: mimemail = MIMEMultipart(msg.get_content_subtype()) for payload in msg.get_payload(): mimemail.attach(payload) return flatten_message(mimemail)
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 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()
def prepare_message( sender_: EmailAddress, recipient_: EmailAddress, subject: typing.Text, text: typing.Text, ) -> MIMEBase: sender = Address(sender_.name, addr_spec=sender_.address) recipient = Address(recipient_.name, addr_spec=recipient_.address) html = markdown.markdown(text) plaintext_message = EmailMessage() plaintext_message["Subject"] = subject plaintext_message["From"] = sender plaintext_message["To"] = (recipient, ) plaintext_message.set_content(text) plaintext_message.add_alternative(html, subtype="html") encrypted_text = encrypt_text(recipient.addr_spec, plaintext_message.as_string()) encrypted_message = MIMEBase(_maintype="multipart", _subtype="encrypted", protocol="application/pgp-encrypted") encrypted_message["Subject"] = subject encrypted_message["From"] = str(sender) encrypted_message["To"] = str(recipient) encrypted_message_part1 = Message() encrypted_message_part1.add_header(_name="Content-Type", _value="application/pgp-encrypted") encrypted_message_part1.add_header( _name="Content-Description", _value="PGP/MIME version identification") encrypted_message_part1.set_payload("Version: 1" + "\n") encrypted_message_part2 = Message() encrypted_message_part2.add_header(_name="Content-Type", _value="application/octet-stream", name="encrypted.asc") encrypted_message_part2.add_header(_name="Content-Description", _value="OpenPGP encrypted message") encrypted_message_part2.add_header(_name="Content-Disposition", _value="inline", filename="encrypted.asc") encrypted_message_part2.set_payload(encrypted_text) encrypted_message.attach(encrypted_message_part1) encrypted_message.attach(encrypted_message_part2) return encrypted_message
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()
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()
def get_mime_payload(msg): if not msg.is_multipart(): mimemail = MIMEBase(msg.get_content_maintype(), msg.get_content_subtype(), charset=msg.get_content_charset()) mimemail.set_payload(msg.get_payload()) if msg.has_key('Content-Transfer-Encoding'): mimemail['Content-Transfer-Encoding'] = msg[ 'Content-Transfer-Encoding'] else: mimemail = MIMEMultipart(msg.get_content_subtype()) for payload in msg.get_payload(): mimemail.attach(payload) return flatten_message(mimemail)
def sendMail(Shelter, reciever): string = "도로명 주소 : " + Shelter.rddr + "\n" string += "지번 주소 : " + Shelter.addr + "\n" string += "시설명 : " + Shelter.facility_name + "\n" imageFileName = "Shild.png" # global value host = "smtp.gmail.com" # Gmail STMP 서버 주소. port = "587" #htmlFileName = "ShildMap.html" senderAddr = "*****@*****.**" # 보내는 사람 email 주소. recipientAddr = reciever # 받는 사람 email 주소. msg = MIMEBase("multipart", "alternative") a = MIMEText(string) msg['Subject'] = "대피소 정보" # 제목 msg['From'] = senderAddr msg['To'] = recipientAddr # MIME 문서를 생성합니다. #htmlFD = open(htmlFileName, 'rb') #HtmlPart = MIMEText(htmlFD.read(), 'html', _charset='UTF-8') #htmlFD.close() imageFD = open(imageFileName, 'rb') ImagePart = MIMEImage(imageFD.read()) imageFD.close() # 만들었던 mime을 MIMEBase에 첨부 시킨다. #msg.attach(HtmlPart) msg.attach(a) msg.attach(ImagePart) # 메일을 발송한다. s = mysmtplib.MySMTP(host, port) # s.set_debuglevel(1) # 디버깅이 필요할 경우 주석을 푼다. s.ehlo() s.starttls() s.ehlo() s.login("*****@*****.**", "ssiber12") s.sendmail(senderAddr, [recipientAddr], msg.as_string()) s.close() pass
def send_mail(from_email, to_email, subject, content, content_type, alias, file=None, cc=None): smtp = smtplib.SMTP_SSL(os.environ.get('SMTP', None)) try: smtp.ehlo() password = os.environ.get('PASSWORD', None) account = os.environ.get('ACCOUNT', None) smtp.login(account, password) msg = MIMEBase('multipart', 'mixed') content = MIMEText(content, content_type, _charset="utf-8") msg['Subject'] = subject msg['From'] = f'{alias} <{from_email}>' if isinstance(to_email, list): msg['To'] = ','.join(to_email) else: msg['To'] = to_email if cc: if isinstance(cc, list): msg['Cc'] = ','.join(cc) else: msg['Cc'] = cc msg.attach(content) if file: part = MIMEBase('application', 'octet-stream') part.set_payload(file.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', f'attachment;filename={file.filename}') msg.attach(part) smtp.sendmail(from_email, to_email, msg.as_string()) except smtplib.SMTPException as e: logger.error(e) raise e finally: smtp.quit()
def _attach_body(self, msg: MIMEBase, body: Optional[str], ids: Optional[List[str]], is_html: bool) -> MIMEBase: """Attach email body to the msg. If gdrive ids are provided, attach gdrive file hyperlinks in the body. The format of the email can be specified to 'html' or 'plain'. :param msg: a MIMEBase object. :param body: body of the email. :param ids: a list of gdrive file ids. :param is_html: whether email should be send in html format or plain text format :return: a msg with body attached. """ if body is not None: body_mime = MIMEText(body, 'html' if is_html else 'plain') msg.attach(body_mime) msg = self._attach_gdrive_files(msg, ids) return msg
def _extractMIMEPayload(self,mail): # Email is non multipart if type(mail.get_payload()) == types.StringType: # duplicate content-type and charset mimemail = MIMEBase(mail.get_content_maintype(),mail.get_content_subtype(),charset=mail.get_content_charset()) mimemail.set_payload(mail.get_payload()) # copy transfer encoding if mail.has_key('Content-Transfer-Encoding'): del mimemail['Content-Transfer-Encoding'] mimemail['Content-Transfer-Encoding'] = mail['Content-Transfer-Encoding'] # for a multipart email just add every sub message else: mimemail = MIMEMultipart("mixed") for payload in mail.get_payload(): mimemail.attach(payload) return Util.flattenMessage(mimemail)
def SendMail(image, text, receiveAddress, title): me = '*****@*****.**' you = receiveAddress contents = text msg = MIMEBase('multipart', 'mixed') msg['Subject'] = title msg['From'] = me msg['To'] = you main = MIMEText(contents) msg.attach(main) img = MIMEImage(image) msg.attach(img) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(me, 'qlalf!1234') s.sendmail(me, you, msg.as_string()) s.close()
def force_display_headers(self, msg, obscured_set): # If we aren't changing the structure of the message (adding a # force-display part), we can just wrap the original and be done. if not [k for k in obscured_set if k.lower() in self.FORCE_DISPLAY_HEADERS]: return msg header_display = MIMEBase('text', 'rfc822-headers', protected_headers="v1") header_display['Content-Disposition'] = 'inline' container = MIMEBase('multipart', 'mixed') container.attach(header_display) container.attach(msg) # Cleanup... for p in (msg, header_display, container): if 'MIME-Version' in p: del p['MIME-Version'] if self.cleaner: self.cleaner(header_display) self.cleaner(msg) # NOTE: The copying happens at the end here, because we need the # cleaner (on msg) to have run first. display_headers = [] to_delete = {} for h, v in msg.items(): hl = h.lower() if not hl.startswith('content-') and not hl.startswith('mime-'): container.add_header(h, v) if hl in self.FORCE_DISPLAY_HEADERS and h in obscured_set: display_headers.append('%s: %s' % (h, v)) to_delete[h] = True for h in to_delete: while h in msg: del msg[h] header_display.set_payload('\r\n'.join(reversed(display_headers))) return container
def force_display_headers(self, msg, headers): if not [k for k in headers.keys() if k.lower() in self.FORCE_DISPLAY_HEADERS]: return msg header_display = MIMEBase('text', 'rfc822-headers', protected_headers="v1") header_display['Content-Disposition'] = 'inline' container = MIMEBase('multipart', 'mixed') container.attach(header_display) container.attach(msg) # Cleanup... for p in (msg, header_display, container): if 'MIME-Version' in p: del p['MIME-Version'] if self.cleaner: self.cleaner(header_display) self.cleaner(msg) # FIXME: Pretty sure this doesn't do the right thing if there # are multiple headers with the same name. # # NOTE: The copying happens at the end here, because we need the # cleaner (on msg) to have run first. # display_headers = [] for h in msg.keys(): hl = h.lower() if not hl.startswith('content-') and not hl.startswith('mime-'): container[h] = msg[h] if hl in self.FORCE_DISPLAY_HEADERS and h in headers: display_headers.append('%s: %s' % (h, msg[h])) del msg[h] header_display.set_payload('\r\n'.join(reversed(display_headers))) return container
def test_attachments(self): text_content = "* Item one\n* Item two\n* Item three" self.message.attach(filename="test.txt", content=text_content, mimetype="text/plain") # Should guess mimetype if not provided... png_content = b"PNG\xb4 pretend this is the contents of a png file" self.message.attach(filename="test.png", content=png_content) # Should work with a MIMEBase object (also tests no filename)... pdf_content = b"PDF\xb4 pretend this is valid pdf data" mimeattachment = MIMEBase('application', 'pdf') mimeattachment.set_payload(pdf_content) self.message.attach(mimeattachment) # And also with an message/rfc822 attachment forwarded_email_content = sample_email_content() forwarded_email = message_from_bytes(forwarded_email_content) rfcmessage = MIMEBase("message", "rfc822") rfcmessage.attach(forwarded_email) self.message.attach(rfcmessage) self.message.send() files = self.get_api_call_files() attachments = [value for (field, value) in files if field == 'attachment'] self.assertEqual(len(attachments), 4) self.assertEqual(attachments[0], ('test.txt', text_content, 'text/plain')) self.assertEqual(attachments[1], ('test.png', png_content, 'image/png')) # type inferred from filename self.assertEqual(attachments[2], (None, pdf_content, 'application/pdf')) # no filename # Email messages can get a bit changed with respect to whitespace characters # in headers, without breaking the message, so we tolerate that: self.assertEqual(attachments[3][0], None) self.assertEqualIgnoringWhitespace( attachments[3][1], b'Content-Type: message/rfc822\nMIME-Version: 1.0\n\n' + forwarded_email_content) self.assertEqual(attachments[3][2], 'message/rfc822') # Make sure the image attachment is not treated as embedded: inlines = [value for (field, value) in files if field == 'inline'] self.assertEqual(len(inlines), 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()
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()
#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()
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()
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")
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()
#imageF.close() # Create MIMEtxt textF=open(textfile,'rb') textPart=MIMEImage(textF.read()) 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()
msg['Subject'] = "Test email in Python 3.0" msg['From'] = senderAddr msg['To'] = recipientAddr #Make MIMEType htmlFD = open(htmlFileName, 'rb') HtmlPart = MIMEText(htmlFD.read(), _charset = 'UTF-8' ) htmlFD.close() imageFD = open(imageFileName, 'rb') ImagePart = MIMEImage(imageFD.read()) imageFD.close() # 만들었던 mime을 MIMEBase에 첨부 시킨다. msg.attach(ImagePart) msg.attach(HtmlPart) #헤더에 첨부 파일에 대한 정보를 추가 시킨다. msg.add_header('Content-Disposition','attachment',filename=imageFileName) msg['Subject'] = "test python email" msg['From'] = senderAddr msg['To'] = recipientAddr #메일을 발송한다. s = smtplib.SMTP(host) s.connect() s.sendmail(senderAddr , [recipientAddr], msg.as_string()) s.close()