From f540db4fba89281cee458e323546d302bf6d503c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=A2=E1=84=91=E1=85=B3=E1=86=AF=20=E1=84=82?= =?UTF-8?q?=E1=85=A9=E1=84=90=E1=85=B3=E1=84=87=E1=85=AE=E1=86=A8?= Date: Thu, 25 Apr 2019 21:15:26 +0900 Subject: [PATCH] Add: sending email to unregistered maestro in PHP --- src/web/php/test.php | 7 + src/web/php/test_ncloud.php | 121 +++++++++++++++ .../python/chocomae/lib/database/module_a.py | 4 - .../chocomae/lib/mail/mail_sender_example.py | 143 ++++++++++++++++++ src/web/python/chocomae/lib/mail/module_b.py | 7 - .../python/chocomae/remove_unpaid_maestro.py | 13 +- 6 files changed, 279 insertions(+), 16 deletions(-) create mode 100755 src/web/php/test.php create mode 100644 src/web/php/test_ncloud.php delete mode 100644 src/web/python/chocomae/lib/database/module_a.py create mode 100644 src/web/python/chocomae/lib/mail/mail_sender_example.py delete mode 100644 src/web/python/chocomae/lib/mail/module_b.py diff --git a/src/web/php/test.php b/src/web/php/test.php new file mode 100755 index 0000000..186eca3 --- /dev/null +++ b/src/web/php/test.php @@ -0,0 +1,7 @@ +#!/usr/bin/php + + diff --git a/src/web/php/test_ncloud.php b/src/web/php/test_ncloud.php new file mode 100644 index 0000000..13360ac --- /dev/null +++ b/src/web/php/test_ncloud.php @@ -0,0 +1,121 @@ + false, // 광고메일여부 default: false + "attachFileIds" => array(), // 첨부파일ID + "body" => "", // Email 본문 + "individual" => false, // 개인발송여부 (개인발송 시 참조인, 숨은참조 무시됨) default: true + "parameters" => array( + "maestro_name" => $maestro_name, + "register_date" => $register_date, + ), // 치환 파라미터 (수신자별로 적용), ‘치환 ID’ 를 key로, ‘치환 ID에 맵핑되는 값’ 을 value로 가지는 Map 형태의 Object + "recipients" => array( + array( + "address" => $maestro_email, // 수신자 Email 주소 + "name" => "", // 수신자 명 + "type" => "R", // 수신자 유형 (R: 수신자, C: 참조인, B: 숨은참조) default: R + // "parameters" => array_map(), + // 치환 파라미터 (수신자별로 적용), ‘치환 ID’ 를 key로, ‘치환 ID에 맵핑되는 값’ 을 value로 가지는 Map 형태의 Object + "parameters" => array( + "maestro_name" => $maestro_name, + ), // 치환 파라미터 (수신자별로 적용), ‘치환 ID’ 를 key로, ‘치환 ID에 맵핑되는 값’ 을 value로 가지는 Map 형태의 Object + ), + ), + "referencesHeader" => "", // 특정 메일을 모아서 보기 위해 네이버 메일에서 지원하는 기능, 해당 필드에 동일한 값을 입력한 메일들을 모아서 볼 수 있다. (다음의 형태가 되어야 함 : ) + "reservationUtc" => "", // 예약 발송 일시 ( 1970년 1월 1일 00:00:00 협정 세계시(UTC) 부터의 경과 시간을 1/1000초로 환산한 정수 ), reservationDateTime 값보다 이 값이 우선 적용된다. + "reservationDateTime" => "", // 다음과 같은 형태의 예약 발송 일시 (‘yyyy-MM-dd HH:mm’ UTC+09:00), reservationUtc 값이 우선한다. + "senderAddress" => "support+chocomae@jinaju.com", // 발송자 Email 주소 + "senderName" => "초코마에", // 발송자 이름 + "tempRequestId" => "", // 첨부파일 등록 시 사용한 임시 요청 ID + "templateSid" => "337", // 템플릿 ID + "title" => "", // Mail 제목 + ); + + $postParam = json_encode($postParam); + echo "json:\n"; + echo $postParam; + echo "\n"; + + $is_post = true; + + $success_code = 201; + } else { + $success_code = 200; + $requestUrl = $requestUrl."/requests/".$requestId."/status"; + } + + $signautue = makeSignature($secretKey, $method, $requestUrl, $timestamp, $accessKey); + + $url = $hostNameUrl.$requestUrl; + echo $url."\n"; + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, $is_post); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + if($method == "POST") { + curl_setopt($ch, CURLOPT_POSTFIELDS, $postParam); + } + $headers = array(); + $headers[] = "X-NCP-APIGW-TIMESTAMP: " .$timestamp; + $headers[] = "X-NCP-IAM-ACCESS-KEY: " .$accessKey; + $headers[] = "X-NCP-APIGW-SIGNATURE-V2: " .$signautue; + $headers[] = "content-type: application/json"; + + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $response = curl_exec ($ch); + $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + echo "status_code:".$status_code."\n"; + curl_close ($ch); + if($status_code == 200) { + echo $response."\n"; + } else { + echo "Error 내용:".$response."\n"; + } + +} catch(Exception $E) { + echo "Response: ". $E->lastResponse . "\n"; +} + +function makeSignature($secretKey, $method, $uri, $timestamp, $accessKey) { + $space = " "; + $newLine = "\n"; + $hmac = $method.$space.$uri.$newLine.$timestamp.$newLine.$accessKey; + $signautue = base64_encode(hash_hmac('sha256', $hmac, $secretKey,true)); + echo "this is signiture : ".$signautue."\n"; + return $signautue; +} +?> \ No newline at end of file diff --git a/src/web/python/chocomae/lib/database/module_a.py b/src/web/python/chocomae/lib/database/module_a.py deleted file mode 100644 index d5aba23..0000000 --- a/src/web/python/chocomae/lib/database/module_a.py +++ /dev/null @@ -1,4 +0,0 @@ - -class ModuleA: - def print(self): - print('module A') \ No newline at end of file diff --git a/src/web/python/chocomae/lib/mail/mail_sender_example.py b/src/web/python/chocomae/lib/mail/mail_sender_example.py new file mode 100644 index 0000000..0839d73 --- /dev/null +++ b/src/web/python/chocomae/lib/mail/mail_sender_example.py @@ -0,0 +1,143 @@ +import time +from datetime import datetime +import json +import requests +import base64 +import hmac +import hashlib + + +class NCloud: + host_name_url = "https://mail.apigw.ntruss.com" # 호스트 URL + request_url = "/api/v1/mails" # 요청 URI + access_key = "qNXWk443wdnDXrkPvoqr" # 네이버 클라우드 플랫폼 회원에게 발급되는 개인 인증키 + secret_key = "umWxQXulhNSya2CkMNqqVJnSRfwRaN8BjMUX0skV" + # 2차 인증을 위해 서비스마다 할당되는 service secret + api_key = "eWfapJfbR5W9NXPEsdXGzlJsShEV30DfxIV0d51J" + # API Gateway에서 발급받은 키(primary key 또는 secondary key) + method = "POST" # 요청 method mail 발송: POST, 발송 확인 GET + request_id = "" # 요청 ID + + +class MailSenderExample: + # new_line = "\r\n" + html_br_tag = "
" + + # mail sender info + sender_name = "초코마에" + sender_email = "support+chocomae@jinaju.com" + sender_address = sender_email + sender_bcc = "support+chocomae.automail@jinaju.com" + + # bank account info + bank_account_no = "3333-07-4977969" + bank_name = "카카오뱅크" + bank_owner_name = "박지상" + + @staticmethod + def get_timestamp(): + time_array = MailSenderExample.micro_time().split(' '); + microtime = time_array[0]; + timestamp = time_array[1]; + # print('microtime : ' + microtime) + # print('timestamp : ' + timestamp) + # print('microtime[2:5] : ' + microtime[2:5]) + return timestamp + microtime[2:5] + + @staticmethod + def micro_time(get_as_float = False): + d = datetime.now() + t = time.mktime(d.timetuple()) + if get_as_float: + return t + else: + ms = d.microsecond / 1000000. + return '%f %d' % (ms, t) + + @staticmethod + def hash_hmac(algo, data, key): + res = hmac.new(key.encode(), data.encode(), algo).hexdigest() + return res + + @staticmethod + def b64encode(source): + source = source.encode('utf=8') + return base64.b64encode(source) + # a = base64.b64encode(bytes(source.encode('utf-8'))) + # b = base64.b64decode(a).decode('utf-8', 'ignore') + # return b + + @staticmethod + def make_signature(secret_key, method, request_url, timestamp, access_key): + space = " " + new_line = "\n" + hmac_data = method + space + request_url + new_line + timestamp + new_line + access_key + print('hmac_data :') + print(hmac_data) + hash_hmac_data = MailSenderExample.hash_hmac(hashlib.sha256, hmac_data, secret_key) + signature = MailSenderExample.b64encode(hash_hmac_data) + # signature = base64.b64encode(bytes(hash_hmac_data, 'utf-8')) + # signature = hash_hmac_data + return signature + + @staticmethod + def send_temp_mail(): + post_param = { + "advertising": False, # 광고메일여부 default: False + "attachFileIds": [], # 첨부파일ID + "body": "mail body", # Email 본문 + "individual": True, # 개인발송여부 (개인발송 시 참조인, 숨은참조 무시됨) default: true + "parameters": [], # 치환 파라미터 (전체 수신자에게 적용), ‘치환 ID’ 를 key로, + # ‘치환 ID에 맵핑되는 값’ 을 value로 가지는 Map 형태의 Object + "recipients": [ + {"address": "jisangs@daum.net", "name": "", "type": "R", "parameters": []} + ], + "referencesHeader": "", # 특정 메일을 모아서 보기 위해 네이버 메일에서 지원하는 기능, + # 해당 필드에 동일한 값을 입력한 메일들을 모아서 볼 수 있다. + # (다음의 형태가 되어야 함 : ) + "reservationUtc": "", # 예약 발송 일시 ( 1970년 1월 1일 00:00:00 협정 세계시(UTC) + # 부터의 경과 시간을 1/1000초로 환산한 정수 ), + # reservationDateTime 값보다 이 값이 우선 적용된다. + "reservationDateTime": "", # 다음과 같은 형태의 예약 발송 일시 (‘yyyy-MM-dd HH:mm’ UTC+09:00), + # reservationUtc 값이 우선한다. + "senderAddress": MailSenderExample.sender_email, + "senderName": MailSenderExample.sender_name, + "tempRequestId": "", # 첨부파일 등록 시 사용한 임시 요청 ID + "templateSid": "337", # 템플릿 ID + "title": "" + } + + # print(post_param) + # print(type(post_param)) + # print('=' * 30) + json_data = json.dumps(post_param) + # print(json_data) + # indent_json = json.dumps(post_param, indent=4) + # print(indent_json) + + timestamp = MailSenderExample.get_timestamp() + # print(timestamp) + signature = MailSenderExample.make_signature(NCloud.secret_key, NCloud.method, NCloud.request_url, timestamp, NCloud.access_key) + print(signature) + + url = NCloud.host_name_url + NCloud.request_url + # print(url) + + headers = { + "X-NCP-APIGW-TIMESTAMP": timestamp, + "X-NCP-IAM-ACCESS-KEY": NCloud.access_key, + "X-NCP-APIGW-SIGNATURE-V2": signature.decode("utf-8"), + "Content-type": "application/json" + } + # print('headers : ' + json.dumps(headers, indent='\t')) + # exit(0) + res = requests.post(url, headers=headers, data=json_data) + + print('#' * 20 + ' result ' + '#' * 20) + print('sending mail result : {0}'.format(res.status_code)) + + print('status : {0}'.format(requests.status_codes._codes[res.status_code])) + print('result text : \n{0}'.format(res.text)) + print('encoding : {0}'.format(res.encoding)) + print('content : {0}'.format(res.content)) + print('json : {0}'.format(res.json())) diff --git a/src/web/python/chocomae/lib/mail/module_b.py b/src/web/python/chocomae/lib/mail/module_b.py deleted file mode 100644 index 999d413..0000000 --- a/src/web/python/chocomae/lib/mail/module_b.py +++ /dev/null @@ -1,7 +0,0 @@ -from lib.database.module_a import ModuleA - - -class ModuleB: - def print(self): - ma = ModuleA() - ma.print() \ No newline at end of file diff --git a/src/web/python/chocomae/remove_unpaid_maestro.py b/src/web/python/chocomae/remove_unpaid_maestro.py index 5d59283..50ff37e 100644 --- a/src/web/python/chocomae/remove_unpaid_maestro.py +++ b/src/web/python/chocomae/remove_unpaid_maestro.py @@ -1,10 +1,13 @@ -from batch.unpaid_maestro_manager import UnpaidMaestroManager -from lib.mail.mail_sender import MailSender +# from batch.unpaid_maestro_manager import UnpaidMaestroManager +# from lib.mail.mail_sender import MailSender +from lib.mail.mail_sender_example import MailSenderExample +''' umMan = UnpaidMaestroManager() maestro_list = umMan.get_unpaid_7days_maestro_list() -for item in maestro_list: - print(item) +# for item in maestro_list: +# print(item) +''' -mailSender = MailSender() +mailSender = MailSenderExample() mailSender.send_temp_mail() \ No newline at end of file