在Python中如何设置邮件主题和正文,并通过smtplib发送
发布时间:2024-01-16 04:12:08
在Python中,可以使用smtplib库发送电子邮件。以下是一个使用smtplib发送带有主题和正文的电子邮件的示例代码。
首先,需要导入必要的模块。
import smtplib from email.mime.text import MIMEText from email.header import Header
然后,需要设置发送者和接收者的电子邮件地址,并创建电子邮件主题和正文。
sender = 'sender@example.com' receivers = ['receiver@example.com'] subject = 'Python Email Test' message = ''' This is the body of the email. Yo can write multiple lines here. '''
接下来,可以使用MIMEText类来创建电子邮件。
msg = MIMEText(message, 'plain', 'utf-8')
然后,需要设置电子邮件的主题和发件人、收件人信息。
msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = ', '.join(receivers)
接下来,可以使用smtplib库来发送电子邮件。
try:
smtpObj = smtplib.SMTP('your.smtp.server')
smtpObj.sendmail(sender, receivers, msg.as_string())
print("Email sent successfully")
except smtplib.SMTPException:
print("Error: Unable to send email")
在以上代码中,需要将your.smtp.server替换为实际的SMTP服务器地址。
完整的例子代码如下:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = 'sender@example.com'
receivers = ['receiver@example.com']
subject = 'Python Email Test'
message = '''
This is the body of the email.
Yo can write multiple lines here.
'''
msg = MIMEText(message, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = ', '.join(receivers)
try:
smtpObj = smtplib.SMTP('your.smtp.server')
smtpObj.sendmail(sender, receivers, msg.as_string())
print("Email sent successfully")
except smtplib.SMTPException:
print("Error: Unable to send email")
运行以上代码,将会发送一个带有主题和正文的电子邮件。
注意:在实际应用中,需要替换示例中的发送者、接收者以及SMTP服务器地址。另外,如果SMTP服务器需要认证,还需要提供用户名和密码进行认证操作。
