SendGrid로 이메일 보내기

이 튜토리얼에서는 SendGrid를 사용하여 Compute Engine 가상 머신(VM) 인스턴스에서 실행되는 앱에서 이메일을 보내는 방법을 보여줍니다.

Postfix로 인스턴스에서 메일 보내기

다음 단계를 완료하여 sendgrid-tutorial 인스턴스에 연결하고 Postfix가 있는 SendGrid를 실행합니다.

SSH를 사용하여 sendgrid-tutorial 인스턴스에 연결

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

SendGrid를 Postfix가 있는 SMTP 릴레이로 구성

SSH 터미널에서 다음 명령어를 실행하여 SendGrid를 Postfix가 있는 SMTP 릴레이로 사용합니다.

  1. 수퍼유저가 됩니다.

    sudo su -
    
  2. 안전한 언마스크를 설정합니다.

    umask 077
    
  3. Postfix Mail Transport Agent를 설치합니다.

    Debian

    apt update && apt -y install postfix libsasl2-modules

    CentOS

    yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y

    메시지가 나타나면 로컬 전용 구성을 선택하고 기본 도메인 이름을 그대로 사용합니다.

  4. Postfix 구성 옵션을 수정합니다. 수정할 /etc/postfix/main.cf를 엽니다. 예를 들어 nano 텍스트 편집기를 사용하려면 다음 명령어를 입력합니다.

    nano /etc/postfix/main.cf
    
  5. 파일을 업데이트합니다.

    1. 다음 줄을 주석 처리합니다.

      # default_transport = error
      # relay_transport = error
      
    2. 파일 끝에 다음 줄을 추가합니다.

      relayhost = [smtp.sendgrid.net]:2525
      smtp_tls_security_level = encrypt
      smtp_sasl_auth_enable = yes
      smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
      header_size_limit = 4096000
      smtp_sasl_security_options = noanonymous
      

      위 줄은 SSL/TLS 지원을 적용하고 이러한 요청에 SMTP 인증을 구성합니다. SASL(단순 액세스 및 보안 계층) 모듈은 Postfix 구성에서 인증을 처리합니다.

  6. 저장하고 파일을 닫습니다.

  7. 시작하기 전에 섹션에서 생성한 API 키를 사용하여 SASL 비밀번호 맵을 생성합니다. your-api-key를 생성한 API 키로 바꿉니다.

    echo [smtp.sendgrid.net]:2525 apikey:your-api-key >> /etc/postfix/sasl_passwd
  8. postmap 유틸리티를 사용하여 .db 파일을 생성합니다.

    postmap /etc/postfix/sasl_passwd
    
  9. .db 파일이 있는지 확인합니다.

    ls -l /etc/postfix/sasl_passwd*
    
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    
  10. 사용자 인증 정보가 들어 있는 파일은 더 이상 필요하지 않으므로 삭제합니다.

    rm /etc/postfix/sasl_passwd
    
  11. .db 파일에 대한 권한을 설정하고 나머지 파일이 삭제되었는지 확인합니다.

    chmod 600 /etc/postfix/sasl_passwd.db
    ls -la /etc/postfix/sasl_passwd*
    
    -rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db
    
  12. 구성을 다시 로드하여 수정된 매개변수를 로드합니다.

    Debian

    /etc/init.d/postfix restart
    

    CentOS

    postfix reload
    

  13. mailutils 또는 mailx 패키지를 설치합니다.

    Debian

    apt -y install mailutils

    CentOS

    yum install mailx -y
    

  14. 테스트 이메일을 전송합니다.

    echo 'message' | mail -s subject email@example.com

    다음을 바꿉니다.

    • message: 이메일의 본문입니다.
    • subject: 이메일의 제목입니다.
    • email@example.com: 메시지를 보내려는 이메일 주소입니다.

    시스템 로그에서 status가 포함된 상태 줄과 성공한 서버 응답 코드 (250)를 찾습니다.

    Debian

    tail -n 5 /var/log/syslog
    

    CentOS

    tail -n 5 /var/log/maillog
    

인스턴스에서 자바를 사용하여 메일 보내기

SSH를 사용하여 sendgrid-tutorial 인스턴스에 연결

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

이메일 메시지 작성 및 보내기

다음 지침에서는 SendGrid Java 클라이언트 라이브러리를 사용하여 SendGrid를 통해 이메일 메시지를 작성하고 전송합니다. 전체 예시는 GitHub에서 볼 수 있습니다.

SSH 터미널에서:

  1. 수퍼유저가 되어 안전한 umask를 설정합니다.

    sudo su -
    umask 077
    
  2. 자바 및 Maven을 설치합니다.

    apt -y update && apt -y install git-core openjdk-11-jdk maven
    
  3. GitHub 저장소를 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
    
  4. 예시의 기본 소스 코드로 이동합니다.

    cd /root/java-docs-samples/compute/sendgrid/src/main/java/com/example/compute/sendgrid
    
  5. 수정할 SendEmailServelet.java을 엽니다.

    • your-sendgrid-api-key를 SendGrid 계정의 API 키로 바꿉니다.

    • your-sendgrid-from-email을 메일을 발신하는 이메일 주소로 바꿉니다.

    • destination-email을 메일을 수신하는 이메일 주소로 바꿉니다.

  6. 샘플 코드의 루트 디렉터리로 이동합니다.

    cd /root/java-docs-samples/compute/sendgrid
    
  7. 자바 클래스를 패키지화합니다.

    mvn clean package
    
  8. target 디렉터리로 이동합니다.

    cd target
    
  9. jar 파일을 실행할 수 있도록 권한을 설정합니다.

    chmod +x compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    
  10. 대체 자바 버전 선택기를 실행합니다.

    update-alternatives --config java
    

    java-11-openjdk-amd64 옵션을 선택합니다.

  11. 자바 파일을 실행합니다.

    java -jar compute-sendgrid-1.0-SNAPSHOT-jar-with-dependencies.jar
    

인스턴스에서 Node.js를 사용하여 메일 보내기

이 샘플을 실행하려면 VM 인스턴스에 Node.js 버전 7.6 이상이 설치되어 있어야 합니다.

SSH를 사용하여 sendgrid-tutorial 인스턴스에 연결

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. In the list of virtual machine instances, click SSH in the row of the instance that you want to connect to.

이메일 메시지 작성 및 보내기

SSH 터미널에서:

  1. 수퍼유저가 되어 안전한 umask를 설정합니다.

    sudo su -
    umask 077
    
  2. 패키지 저장소를 업데이트합니다.

    Debian

    apt update
    

    CentOS

    yum update -y
    

  3. Node.js 종속 항목을 설치합니다.

    Debian

    apt -y install git-core curl build-essential openssl libssl-dev
    

    CentOS

    yum install git-core curl openssl openssl-devel -y
    yum groupinstall "Development Tools" -y
    

  4. Node.js를 설치합니다. 기본적으로 npm도 설치됩니다.

    Debian

    curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
    sudo apt -y install nodejs
    

    CentOS

    curl --silent --location https://rpm.nodesource.com/setup_14.x | bash -
    

    그런 다음 Node.js를 설치합니다.

    yum -y install nodejs
    

  5. SendGrid Node.js 클라이언트를 설치합니다.

    npm install sendgrid
    
  6. 샘플 저장소를 클론합니다.

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
    
  7. SendGrid 샘플이 있는 디렉터리로 이동합니다.

    cd nodejs-docs-samples/compute
    
  8. sendgrid.js 파일을 복사합니다.

    cp sendgrid.js sendmail.js
    
  9. 수정할 sendmail.js을 엽니다.

    • your-sendgrid-api-key를 SendGrid 계정의 API 키로 바꿉니다.

    • from-email@example.com을 메일을 발신하는 이메일 주소로 바꿉니다.

    • to-email@example.com을 메일을 수신하는 이메일 주소로 바꿉니다.

    // This sample is based off of:
    // https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail
    const sendgrid = require('@sendgrid/mail');
    sendgrid.setApiKey(process.env.SENDGRID_API_KEY || '<your-sendgrid-api-key>');
    
    async function sendgridExample() {
      await sendgrid.send({
        to: 'to_email@example.com',
        from: 'from_email@example.com',
        subject: 'Sendgrid test email from Node.js on Google Cloud Platform',
        text: 'Well hello! This is a Sendgrid test email from Node.js on Google Cloud Platform.',
      });
    }
    sendgridExample();

  10. SendGrid를 통해 이메일 메시지를 전송하는 프로그램을 실행합니다.

    node sendmail.js
    

Exchange 에지 전송 서버에서 메일 보내기

아웃바운드 전송 커넥터를 구성하여 Microsoft Exchange에서 SendGrid로 아웃바운드 이메일을 전송하도록 설정할 수 있습니다. 자세한 내용은 Compute Engine에 Microsoft Exchange Server 2016 배포하기를 참조하세요.