|
Python提供了多种发送电子邮件的方式,一些常见的方法及其代码汇总:文章目录1.使用`smtplib`模块2.使用`yagmail`库3.使用`email`模块和`smtplib`4.使用`flask-mail`库(适用于Flask应用)5.使用`smtplib`和`email`模块的结合(高级用法)6.使用`secure-smtplib`7.使用`mailgun`库8.使用`sendgrid`库9.使用`AWSSES`(AmazonSimpleEmailService)10.使用`django.core.mail`(Django项目)11.使用`EmailHandle`12.使用`exchangelib`13.使用`SimpleEmail`14.使用`outlook`库15.使用`zoho-mail`1.使用smtplib模块smtplib是Python内置的一个模块,用于发送邮件。下面是一个使用smtplib发送简单文本邮件的示例:importsmtplibfromemail.mime.textimportMIMETextfromemail.mime.multipartimportMIMEMultipartdefsend_email_smtp():sender_email="your_email@example.com"receiver_email="receiver_email@example.com"password="your_password"#创建邮件对象message=MIMEMultipart()message["From"]=sender_emailmessage["To"]=receiver_emailmessage["Subject"]="TestEmailfromsmtplib"#邮件正文body="ThisisatestemailsentfromPythonusingsmtplib."message.attach(MIMEText(body,"plain"))try:#连接到SMTP服务器server=smtplib.SMTP("smtp.example.com",587)server.starttls()#启用安全传输server.login(sender_email,password)#发送邮件server.sendmail(sender_email,receiver_email,message.as_string())print("Emailsentsuccessfully!")exceptExceptionase:print(f"Error:{e}")finally:server.quit()send_email_smtp()12345678910111213141516171819202122232425262728293031323334352.使用yagmail库yagmail是一个简化的第三方库,用于发送电子邮件。它封装了smtplib,使发送邮件更加容易。首先,安装yagmail库:pipinstallyagmail1然后,使用以下代码发送邮件:importyagmaildefsend_email_yagmail():sender_email="your_email@example.com"password="your_password"receiver_email="receiver_email@example.com"yag=yagmail.SMTP(user=sender_email,password=password)subject="TestEmailfromyagmail"contents="ThisisatestemailsentfromPythonusingyagmail."try:yag.send(to=receiver_email,subject=subject,contents=contents)print("Emailsentsuccessfully!")exceptExceptionase:print(f"Error:{e}")send_email_yagmail()123456789101112131415161718193.使用email模块和smtplibemail模块提供了一个用于构建复杂邮件内容的接口,可以结合smtplib发送邮件。importsmtplibfromemail.messageimportEmailMessagedefsend_email_email_module():sender_email="your_email@example.com"receiver_email="receiver_email@example.com"password="your_password"#创建邮件对象message=EmailMessage()message.set_content("ThisisatestemailsentfromPythonusingemailmoduleandsmtplib.")message["Subject"]="TestEmail"message["From"]=sender_emailmessage["To"]=receiver_emailtry:#连接到SMTP服务器server=smtplib.SMTP("smtp.example.com",587)server.starttls()#启用安全传输server.login(sender_email,password)#发送邮件server.send_message(message)print("Emailsentsuccessfully!")exceptExceptionase:print(f"Error:{e}")finally:server.quit()send_email_email_module()123456789101112131415161718192021222324252627282930314.使用flask-mail库(适用于Flask应用)flask-mail是一个Flask扩展,用于在Flask应用中发送电子邮件。首先,安装flask-mail:pipinstallFlask-Mail1然后,使用以下代码在Flask应用中发送邮件:fromflaskimportFlaskfromflask_mailimportMail,Messageapp=Flask(__name__)app.config['MAIL_SERVER']='smtp.example.com'app.config['MAIL_PORT']=587app.config123456
|
|