How can we automate sending emails using Python?
To automate sending emails, the smtplib module in Python can be used.
Here is a basic sample code that can be used to send emails:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发件人邮箱
sender = 'your_email@example.com'
# 收件人邮箱
receivers = ['recipient1@example.com', 'recipient2@example.com']
# 创建一个带有邮件内容的对象
message = MIMEText('这是邮件的内容', 'plain', 'utf-8')
message['From'] = Header('发件人名称', 'utf-8')
message['To'] = Header('收件人名称', 'utf-8')
message['Subject'] = Header('邮件主题', 'utf-8')
# 发送邮件
try:
smtpObj = smtplib.SMTP('smtp.example.com')
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
In the code, the following content needs to be replaced:
- “one who sends”
- recipients
- communication
It is important to note that the parameters for smtplib.SMTP need to be set with the correct SMTP server address. For example, when using Gmail to send emails, you can replace smtp.example.com with smtp.gmail.com and use the respective port number and username/password for authentication.
In addition, you can also set other properties of the message object, such as Cc (carbon copy), Bcc (blind carbon copy), and attachments. For more detailed information, you can refer to the Python official documentation and the documentation of the smtplib module.