Python郵件開(kāi)發(fā)是一項(xiàng)非常重要的技能,特別是在如今互聯(lián)網(wǎng)時(shí)代,每個(gè)人都需要發(fā)送和接收電子郵件。Python提供了多個(gè)模塊,可以輕松地在Python中發(fā)送電子郵件。在本文中,我將重點(diǎn)介紹Python的smtplib和email模塊,這兩個(gè)模塊可幫助您在Python中輕松地開(kāi)發(fā)郵件應(yīng)用程序。
使用smtplib模塊
Python smtplib模塊允許開(kāi)發(fā)者使用SMTP發(fā)送電子郵件。在使用smtplib發(fā)送電子郵件之前,需要安裝Python的smtplib包。下面是一個(gè)使用smtplib發(fā)送電子郵件的示例:
import smtplib
sender_email = "example_sender_email@domain.com"
receiver_email = "example_receiver_email@domain.com"
password = "example_password"
message = "Hello, this is the message body!"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("Email sent successfully!")
server.quit()
使用email模塊
Python email模塊允許開(kāi)發(fā)者創(chuàng)建和解析電子郵件消息。在使用email模塊之前,需要安裝email包。下面是一個(gè)構(gòu)建郵件的示例:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
sender_email = "example_sender_email@domain.com"
receiver_email = "example_receiver_email@domain.com"
password = "example_password"
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Example Subject'
message.attach(MIMEText('Hello, this is the message body!'))
with open('example_image.jpg', 'rb') as f:
image = MIMEImage(f.read())
message.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
print("Email sent successfully!")
server.quit()
以上代碼展示了如何在Python中使用email模塊創(chuàng)建一個(gè)包含文本和圖像的電子郵件。
上一篇css圖片上覆蓋顏色