在 AWS Lambda 中连接外部 SMTP 服务器需要特殊配置以便可以正常工作。可以按照以下步骤进行操作:
1.在控制台上创建自定义VPC
2.将AWS Lambda添加到此自定义VPC中
3.在VPC中设置Internet Gateway
4.创建SOC2 、PCI 等合规性安全组
5.在Lambda中设置“subnet”和“security group”,以允许Lambda连接SMTP服务器。
示例代码:
import smtplib
def send_mail(): to_email = 'example@domain.com' from_email = 'noreply@domain.com' subject = 'Lambda SMTP Test' body = 'Lambda SMTP test email body' message = 'Subject: {}\n\n{}'.format(subject, body)
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'
try:
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.sendmail(from_email, to_email, message)
print('SMTP email sent successfully')
except Exception as e:
print('Error:', e)
send_mail()