Heroku (PHP) 무료 프레임으로 매일 고양이 이미지를 정기적으로 메일 보내기
12672 단어 경 6PHPheroku schedulerSendGridcatapi
완성형
이런 느낌의 고양이 이미지 메일을 매일 특정 시간에 전달한다. 고양이 이미지는 매일 매일 바뀝니다.

시스템 환경
이름
설명
URL
Heroku
애플리케이션 실행 환경(PaaS)
htps : // jp. 헤로쿠. 코m/
Twilio SendGrid
Heroku 애드온. 메일 발송 서비스
htps : // 에메멘 ts. 헤로쿠. 코 m / 아동 s / 센 dg 리 d
Heroku Scheduler
Heroku 애드온. 정기 실행과 같은 스케줄러 서비스
htps : // 에메멘 ts. 헤로쿠. 코 m / 아동 s / s 치 즈 ぇ r
The Cat API
고양이 이미지를 얻을 수있는 서비스
h tps : /// ぇ카타피. 코m/
구축 절차
1. Heroku 환경 구축
Heroku 스타터 가이드 (PHP) 을 참고로 PHP 환경을 구축한다.
앱 준비
명령 프롬프트>mkdir nekoproject
>cd nekoproject
>git clone https://github.com/heroku/php-getting-started.git
>cd php-getting-started
앱 배포
명령 프롬프트>heroku create
>git push heroku main
>heroku open
heorku open에서 다음과 같은 화면이 표시되면 배포 성공.

2. The Cat API의 API 키 가져오기
htps : /// ぇ카타피. 코m/로 이동하여 "SIGN UP FOR FREE"를 클릭하고 이메일 주소를 입력하면 잠시 후 API 키가 전송됩니다.
취득한 API 키를 URL에 추가해 액세스. 결과의 JSON 파일을 디코드하고 이하의 코드로 고양이 이미지의 URL을 취득할 수 있다.
PHP// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=***********');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
3. Twilio SendGrid(메일 서비스) 설정
애드온 추가
SendGrid의 추가 기능을 프로비저닝합니다. (Heroku에서는 애드온 프로비저닝에 신용 카드 등록이 필요합니다)
명령 프롬프트heroku addons:create sendgrid:starter
SendGrid API Key 가져오기 및 설정
SendGrid로 미리 계정을 등록한다. (심사에 며칠 정도 걸립니다)
SendGrid 제어판을 열고 Settings → API Keys를 엽니다. 그리고, 「Create API Key」를 눌러, Full Access의 API Key를 작성한다.
다음의 커멘드로 환경 변수에 작성한 API Key를 설정한다.
명령 프롬프트heroku config:set SENDGRID_API_KEY=*****************************
SendGrid를 PHP에서 사용하기위한 라이브러리 설치
composer.json을 편집하고 "sendgrid/sendgrid": "~7"줄을 추가합니다.
composer.json{
"require" : {
"silex/silex": "^2.0.4",
"monolog/monolog": "^1.22",
"twig/twig": "^2.0",
"symfony/twig-bridge": "^3",
"sendgrid/sendgrid": "~7"
},
"require-dev": {
"heroku/heroku-buildpack-php": "*"
}
}
다음 명령으로 composer를 업데이트하고 라이브러리를 설치합니다.
명령 프롬프트composer update
4. 소스 코드 배포
다음 코드를 catmail.php로 php-getting-started 바로 아래에 놓습니다. (Cat API의 Key와 메일의 송신원, 송신처의 주소는 적절히 재기록해 주세요)
catmail.php<?php
require 'vendor/autoload.php';
// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=******');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
// Set the email parameters
$email = new \SendGrid\Mail\Mail();
$email->setFrom("***@gmail.com");
$email->setSubject("今日の猫です");
$email->addTo("****@gmail.com");
$email->addContent("text/html", "<img width='300' src='" . $url . "'/>");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
// Send the email
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
echo "email sent!\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
배포합니다.
명령 프롬프트git add .
git commit -m "NEKO"
git push heroku main
다음을 실행하여 메일이 도착하면 성공.
명령 프롬프트heroku run "php catmail.php"
5. 스케줄러 등록
애드온 추가
스케줄러의 추가 기능을 프로비저닝합니다.
명령 프롬프트heroku addons:create scheduler:standard
스케줄러 등록
Heroku의 콘솔 화면에서 Resorce → Heroku Scheduler를 열고 Create Job 버튼을 클릭합니다.
이번에는 다음 화면과 같이 매일 13시에 catmail.php가 실행되도록 설정했다. (협정 세계시(UTC)에서 시각을 설정할 필요가 있기 때문에, 9시간 마이너스한 시각을 설정)

참고 사이트
Heroku 스타터 가이드 (PHP)
고양이의 이미지가 잇달아 닿는 서버리스 시스템
Heroku PHP에서 SendGrid를 사용하여 메일 보내기 첨부 파일도 가능
GitHub - sendgrid/sendgrid-php: The Official Twilio SendGrid Led, Community Driven PHP API Library
Heroku에서 스케줄러(cron)를 설정하는 방법 【Heroku Scheduler】
Reference
이 문제에 관하여(Heroku (PHP) 무료 프레임으로 매일 고양이 이미지를 정기적으로 메일 보내기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/kshimiz/items/47321a80187facd4d44e
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
이름
설명
URL
Heroku
애플리케이션 실행 환경(PaaS)
htps : // jp. 헤로쿠. 코m/
Twilio SendGrid
Heroku 애드온. 메일 발송 서비스
htps : // 에메멘 ts. 헤로쿠. 코 m / 아동 s / 센 dg 리 d
Heroku Scheduler
Heroku 애드온. 정기 실행과 같은 스케줄러 서비스
htps : // 에메멘 ts. 헤로쿠. 코 m / 아동 s / s 치 즈 ぇ r
The Cat API
고양이 이미지를 얻을 수있는 서비스
h tps : /// ぇ카타피. 코m/
구축 절차
1. Heroku 환경 구축
Heroku 스타터 가이드 (PHP) 을 참고로 PHP 환경을 구축한다.
앱 준비
명령 프롬프트>mkdir nekoproject
>cd nekoproject
>git clone https://github.com/heroku/php-getting-started.git
>cd php-getting-started
앱 배포
명령 프롬프트>heroku create
>git push heroku main
>heroku open
heorku open에서 다음과 같은 화면이 표시되면 배포 성공.

2. The Cat API의 API 키 가져오기
htps : /// ぇ카타피. 코m/로 이동하여 "SIGN UP FOR FREE"를 클릭하고 이메일 주소를 입력하면 잠시 후 API 키가 전송됩니다.
취득한 API 키를 URL에 추가해 액세스. 결과의 JSON 파일을 디코드하고 이하의 코드로 고양이 이미지의 URL을 취득할 수 있다.
PHP// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=***********');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
3. Twilio SendGrid(메일 서비스) 설정
애드온 추가
SendGrid의 추가 기능을 프로비저닝합니다. (Heroku에서는 애드온 프로비저닝에 신용 카드 등록이 필요합니다)
명령 프롬프트heroku addons:create sendgrid:starter
SendGrid API Key 가져오기 및 설정
SendGrid로 미리 계정을 등록한다. (심사에 며칠 정도 걸립니다)
SendGrid 제어판을 열고 Settings → API Keys를 엽니다. 그리고, 「Create API Key」를 눌러, Full Access의 API Key를 작성한다.
다음의 커멘드로 환경 변수에 작성한 API Key를 설정한다.
명령 프롬프트heroku config:set SENDGRID_API_KEY=*****************************
SendGrid를 PHP에서 사용하기위한 라이브러리 설치
composer.json을 편집하고 "sendgrid/sendgrid": "~7"줄을 추가합니다.
composer.json{
"require" : {
"silex/silex": "^2.0.4",
"monolog/monolog": "^1.22",
"twig/twig": "^2.0",
"symfony/twig-bridge": "^3",
"sendgrid/sendgrid": "~7"
},
"require-dev": {
"heroku/heroku-buildpack-php": "*"
}
}
다음 명령으로 composer를 업데이트하고 라이브러리를 설치합니다.
명령 프롬프트composer update
4. 소스 코드 배포
다음 코드를 catmail.php로 php-getting-started 바로 아래에 놓습니다. (Cat API의 Key와 메일의 송신원, 송신처의 주소는 적절히 재기록해 주세요)
catmail.php<?php
require 'vendor/autoload.php';
// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=******');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
// Set the email parameters
$email = new \SendGrid\Mail\Mail();
$email->setFrom("***@gmail.com");
$email->setSubject("今日の猫です");
$email->addTo("****@gmail.com");
$email->addContent("text/html", "<img width='300' src='" . $url . "'/>");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
// Send the email
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
echo "email sent!\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
배포합니다.
명령 프롬프트git add .
git commit -m "NEKO"
git push heroku main
다음을 실행하여 메일이 도착하면 성공.
명령 프롬프트heroku run "php catmail.php"
5. 스케줄러 등록
애드온 추가
스케줄러의 추가 기능을 프로비저닝합니다.
명령 프롬프트heroku addons:create scheduler:standard
스케줄러 등록
Heroku의 콘솔 화면에서 Resorce → Heroku Scheduler를 열고 Create Job 버튼을 클릭합니다.
이번에는 다음 화면과 같이 매일 13시에 catmail.php가 실행되도록 설정했다. (협정 세계시(UTC)에서 시각을 설정할 필요가 있기 때문에, 9시간 마이너스한 시각을 설정)

참고 사이트
Heroku 스타터 가이드 (PHP)
고양이의 이미지가 잇달아 닿는 서버리스 시스템
Heroku PHP에서 SendGrid를 사용하여 메일 보내기 첨부 파일도 가능
GitHub - sendgrid/sendgrid-php: The Official Twilio SendGrid Led, Community Driven PHP API Library
Heroku에서 스케줄러(cron)를 설정하는 방법 【Heroku Scheduler】
Reference
이 문제에 관하여(Heroku (PHP) 무료 프레임으로 매일 고양이 이미지를 정기적으로 메일 보내기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/kshimiz/items/47321a80187facd4d44e
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
>mkdir nekoproject
>cd nekoproject
>git clone https://github.com/heroku/php-getting-started.git
>cd php-getting-started
>heroku create
>git push heroku main
>heroku open
// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=***********');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
heroku addons:create sendgrid:starter
heroku config:set SENDGRID_API_KEY=*****************************
{
"require" : {
"silex/silex": "^2.0.4",
"monolog/monolog": "^1.22",
"twig/twig": "^2.0",
"symfony/twig-bridge": "^3",
"sendgrid/sendgrid": "~7"
},
"require-dev": {
"heroku/heroku-buildpack-php": "*"
}
}
composer update
<?php
require 'vendor/autoload.php';
// Get a cat image
$json = file_get_contents('https://api.thecatapi.com/v1/images/search?api_key=******');
$arr = json_decode($json,true);
$url = $arr[0]['url'];
// Set the email parameters
$email = new \SendGrid\Mail\Mail();
$email->setFrom("***@gmail.com");
$email->setSubject("今日の猫です");
$email->addTo("****@gmail.com");
$email->addContent("text/html", "<img width='300' src='" . $url . "'/>");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
// Send the email
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
echo "email sent!\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
git add .
git commit -m "NEKO"
git push heroku main
heroku run "php catmail.php"
heroku addons:create scheduler:standard
Reference
이 문제에 관하여(Heroku (PHP) 무료 프레임으로 매일 고양이 이미지를 정기적으로 메일 보내기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/kshimiz/items/47321a80187facd4d44e텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)