首先,我们需要准备好一个可用的邮箱账号,这里以Gmail为例。然后,我们需要使用Python的smtplib库来进行邮件的发送。
以下是实现邮件发送的完整步骤:
1. 导入必要的库
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
2. 配置邮箱账号信息
username = "your_email_address@gmail.com"
password = "your_email_password"
smtp_server = "smtp.gmail.com"
smtp_port = 587
3. 创建邮件模板
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = 'recipient_email_address@gmail.com'
msg['Subject'] = '邮件标题'
body = "邮件正文"
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open('attachment.txt', 'rb') as f:
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.attach(attachment)
# 添加图片
with open('image.png', 'rb') as f:
image = MIMEImage(f.read())
image.add_header('Content-ID', '<image1>')
msg.attach(image)
4. 发送邮件
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, msg['To'], msg.as_string())
server.quit()
以上就是实现邮件发送的完整步骤。
以下是两条示例说明:
示例1:发送文本邮件
import smtplib
from email.mime.text import MIMEText
username = "your_email_address@gmail.com"
password = "your_email_password"
smtp_server = "smtp.gmail.com"
smtp_port = 587
msg = MIMEText('邮件正文', 'plain')
msg['Subject'] = '邮件标题'
msg['From'] = username
msg['To'] = 'recipient_email_address@gmail.com'
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, msg['To'], msg.as_string())
server.quit()
示例2:发送带附件和图片的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
username = "your_email_address@gmail.com"
password = "your_email_password"
smtp_server = "smtp.gmail.com"
smtp_port = 587
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = 'recipient_email_address@gmail.com'
msg['Subject'] = '邮件标题'
body = "邮件正文"
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open('attachment.txt', 'rb') as f:
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.attach(attachment)
# 添加图片
with open('image.png', 'rb') as f:
image = MIMEImage(f.read())
image.add_header('Content-ID', '<image1>')
msg.attach(image)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, msg['To'], msg.as_string())
server.quit()
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python实现邮箱发送信息 - Python技术站