如何使用python批量发送电子邮件?

How to send emails in bulk using python?

提问人: 提问时间:10/12/2023 更新时间:10/12/2023 访问量:71

问:

我做了一个 django 网站,我想把它推向世界。我想与各种 youtuber 取得联系以推广我的网站,所以我编写了以下代码,这些代码应该向他们所有人发送电子邮件。

from email.message import EmailMessage
import ssl
import smtplib
import time

email_sender = '[email protected]'
with open('google_password.txt') as f:
    email_password = f.read()
subject = 'Subject of the email'
body = """
Contents of my email

"""
def send_email(email_receiver):
   
    em = EmailMessage()
    em['From'] = email_sender
    em['To'] = email_receiver
    em['Subject'] = subject
    em.set_content(body)

    context = ssl.create_default_context()

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
        smtp.login(email_sender, email_password)
        smtp.sendmail(email_sender, email_receiver, em.as_string())

email_receivers = [
'53 separate strings containing the emails of 53 youtubers'
]

for email_receiver in email_receivers:
    try:    
        send_email(email_receiver)
        print("Email sent for:", email_receiver)
    except Exception:
        continue
    finally:
        time.sleep(300)

print("Sent all emails.")

其中一些电子邮件是我的,因为我想检查电子邮件是否在我的垃圾邮件文件夹中发送,情况确实如此。电子邮件在垃圾邮件文件夹中发送。我想知道如何使用 python 正确发送大量电子邮件(而且是免费的,因为我破产了),而不会将它们发送到垃圾邮件文件夹中。一些人推荐了Amazon SES,Mailgun等服务,但我试图了解它们是如何工作的,但我不能,所以请通过描述我应该如何解决这个问题来帮助我!

python 电子邮件 smtp gmail

评论


答:

0赞 Shriyash Warghade 10/12/2023 #1

您可以将 AWS SES 与 AWS Lambda 结合使用

import boto3

def send_email(subject, body, recipient, sender):
    ses = boto3.client('ses', region_name='your_region')  # Replace 'your_region' with your AWS region (e.g., 'us-east-1')

    response = ses.send_email(
    Source=sender,
    Destination={
        'ToAddresses': [
            recipient,
        ],
    },
    Message={
        'Subject': {
            'Data': subject,
        },
        'Body': {
            'Text': {
                'Data': body,
            },
        },
    }
)

return response

def lambda_handler(event, context):
    subject = "Test Email from Lambda"
    body = "This is a test email sent from AWS Lambda using SES."
    recipient = "[email protected]"  # Replace with the recipient's email address
    sender = "[email protected]"  # Replace with the verified sender's email address

    response = send_email(subject, body, recipient, sender)

return {
    'statusCode': 200,
    'body': 'Email sent successfully!',
    'ses_response': response
}

您可以参考设置 SES

注意:请务必确保 Lambda 执行角色已配置了使用 SES 发送电子邮件所需的权限。