Gerar credenciais SMTP a partir de credenciais da IAM existentes
Para enviar e-mail usando a interface SMTP do Amazon SES, você precisa criar um nome de usuário e senha SMTP. A maneira mais fácil de criar nome de usuário e senha do SMTP é usar o console do Amazon SES. Para obter mais informações, consulte Obter as credenciais SMTP do Amazon SES usando o console do Amazon SES.
Algumas linguagens de programação incluem bibliotecas que você pode usar para converter uma chave de acesso secreta do IAM em uma senha SMTP. Se você já tiver um usuário do IAM que deseja usar para enviar e-mails por meio da interface SMTP, você pode usar esses exemplos de código para converter a chave de acesso secreta da AWS para esse usuário em uma senha SMTP.
Antes de executar esses exemplos, coloque a chave de acesso secreta da AWS que você
deseja converter em uma variável de ambiente chamada AWS_SECRET_ACCESS_KEY. Esses exemplos de código transmitem sua senha SMTP convertida como sua saída. Essa
senha e o nome de usuário do SMTP (que é o mesmo que o ID da chave de acesso da AWS)
são suas credenciais SMTP do Amazon SES.
- Bash
#!/usr/bin/env bash # These variables are required to calculate the SMTP password. VERSION='\x02' MESSAGE='SendRawEmail' # Check to see if OpenSSL is installed. If not, exit with errors. if ! [[ -x "$(command -v openssl)" ]]; then echo "Error: OpenSSL isn't installed." >&2 exit 1 # If OpenSSL is installed, check to see that the environment variable has a # length greater than 0. If not, exit with errors. elif [[ -z "${AWS_SECRET_ACCESS_KEY}" ]]; then echo "Error: Couldn't find environment variable AWS_SECRET_ACCESS_KEY." >&2 exit 1 fi # If we made it this far, all of the required elements exist. # Calculate the SMTP password. (echo -en $VERSION; echo -n $MESSAGE \ | openssl dgst -sha256 -hmac $AWS_SECRET_ACCESS_KEY -binary) \ | openssl enc -base64- Java
import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; public class SesSmtpCredentialGenerator { // Put your AWS secret access key in this environment variable. private static final String KEY_ENV_VARIABLE = "AWS_SECRET_ACCESS_KEY"; // Used to generate the HMAC signature. Do not modify. private static final String MESSAGE = "SendRawEmail"; // Version number. Do not modify. private static final byte VERSION = 0x02; public static void main(String[] args) { // Get the AWS secret access key from environment variable AWS_SECRET_ACCESS_KEY. String key = System.getenv(KEY_ENV_VARIABLE); if (key == null) { System.out.println("Error: Cannot find environment variable AWS_SECRET_ACCESS_KEY."); System.exit(0); } // Create an HMAC-SHA256 key from the raw bytes of the AWS secret access key. SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256"); try { // Get an HMAC-SHA256 Mac instance and initialize it with the AWS secret access key. Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKey); // Compute the HMAC signature on the input data bytes. byte[] rawSignature = mac.doFinal(MESSAGE.getBytes()); // Prepend the version number to the signature. byte[] rawSignatureWithVersion = new byte[rawSignature.length + 1]; byte[] versionArray = {VERSION}; System.arraycopy(versionArray, 0, rawSignatureWithVersion, 0, 1); System.arraycopy(rawSignature, 0, rawSignatureWithVersion, 1, rawSignature.length); // To get the final SMTP password, convert the HMAC signature to base 64. String smtpPassword = DatatypeConverter.printBase64Binary(rawSignatureWithVersion); System.out.println(smtpPassword); } catch (Exception ex) { System.out.println("Error generating SMTP password: " + ex.getMessage()); } } }- Python
import os #required to fetch environment varibles import hmac #required to compute the HMAC key import hashlib #required to create a SHA256 hash import base64 #required to encode the computed key import sys #required for system functions (exiting, in this case) # Fetch the environment variable called AWS_SECRET_ACCESS_KEY, which contains # the secret access key for your IAM user. key = os.getenv('AWS_SECRET_ACCESS_KEY',0) # These varibles are used when calculating the SMTP password. You shouldn't # change them. message = 'SendRawEmail' version = '\x02' # See if the environment variable exists. If not, quit and show an error. if key == 0: sys.exit("Error: Can't find environment variable AWS_SECRET_ACCESS_KEY.") # Compute an HMAC-SHA256 key from the AWS secret access key. signatureInBytes = hmac.new(key.encode('utf-8'),message.encode('utf-8'),hashlib.sha256).digest() # Prepend the version number to the signature. signatureAndVersion = version.encode('utf-8') + signatureInBytes # Base64-encode the string that contains the version number and signature. smtpPassword = base64.b64encode(signatureAndVersion) # Decode the string and print it to the console. print(smtpPassword.decode('utf-8'))
