汇总Python发邮件的15个常用方式(附代码)
在Python中,发送电子邮件的方法有很多,以下是15种常见的方法:
- 使用内置的smtplib模块
import smtplib
def send_email(to, subject, body):
email_user = 'youremail@gmail.com'
email_password = 'your_password'
sender_email = 'youremail@gmail.com'
receiver_email = to
message = f"Subject: {subject}\n\n{body}"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(sender_email, receiver_email, message)
server.quit()
send_email('test@test.com', 'Test Subject', 'Test Body')
- 使用内置的smtplib模块和ssl
import smtplib
import ssl
def send_email(to, subject, body):
email_user = 'youremail@gmail.com'
email_password = 'your_password'
sender_email = 'youremail@gmail.com'
receiver_email = to
message = f"Subject: {subject}\n\n{body}"
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
server.login(email_user, email_password)
server.sendmail(sender_email, receiver_email, message)
send_email('test@test.com', 'Test Subject', 'Test Body')
- 使用内置的smtplib模块和starttls
import smtplib
def send_email(to, subject, body):
email_user = 'youremail@gmail.com'
email_password = 'your_password'
sender_email = 'youremail@gmail.com'
receiver_email = to
message = f"Subject: {subject}\n\n{body}"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(sender_email, receiver_email, message)
server.quit()
send_email('test@test.com', 'Test Subject', 'Test Body')
- 使用内置的smtplib模块和ssl.create\_default\_context
import smtplib
import ssl
def send_email(to, subject, body):
email_user = 'youremail@gmail.com'
email_password = 'your_password'
sender_email = 'youremail@gmail.com'
receiver_email = to
message = f"Subject: {subject}\n\n{body}"
context = ssl.create_default_contex
评论已关闭