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

问题描述 投票:0回答:1

我制作了一个 Django 网站,我想将其发布到全世界。我想与各种 YouTube 用户联系来推广我的网站,因此我编写了以下代码,该代码应该向他们所有人发送电子邮件。

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 email smtp gmail
1个回答
0
投票

您可以将 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
}

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

© www.soinside.com 2019 - 2024. All rights reserved.