Gmail 邮箱python自动发送邮件

反正就是要给一批人发送内容差不多的邮件, 手上只有文本格式的每个人的email address和对应的message.
写了很久了,弄出来以后好看。。
反正gmail的话,得到邮箱选项里设置几个东西(降低自己账户安全等级)。否则有可能发不出去,或者是发几十封之后账户被锁。。。

import smtplib
import ssl
from email import encoders
from email.mime.multipart import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time

from utils import mail_generator

sender_email = '[email protected]'
password = 'xxxxxxxx'

context = ssl.create_default_context()

# 端口465好像是在gmail官方说明里查的,具体忘了
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)

    def send_mail(subject, mail_text, mail_address):

        message = MIMEMultipart("alternative")
        message["Subject"] = subject
        message["From"] = sender_email
        message["To"] = mail_address
        text = mail_text
        part1 = MIMEText(text, "plain")
        message.attach(part1)

        text = message.as_string()

        server.sendmail(
            sender_email, mail_address, message.as_string())

    for info in mail_generator():
        mail_text, receiver, mail_address, sID = info
        
        subject = f"给{receiver}{sID}的邮件标题"
        send_mail(subject, mail_text, mail_address)
        time.sleep(3)    # 停3秒发一封,但是还是建议调更大一点儿
        print(subject+"sended!!!!!!")

你可能感兴趣的:(Gmail 邮箱python自动发送邮件)