python smtp实例

本文介绍了一个用Python编写的简单SMTP邮件发送脚本。通过smtplib模块和email.mime.text.MIMEText类,实现向指定邮箱发送纯文本内容的邮件。文章提供了一个完整的示例代码,并附带了错误处理逻辑。

先来个大栗子:

# Description: Simple smtp test
# Author: xumesang
# Date: 2016-11-7

import smtplib
from email.mime.text import MIMEText
mailto_list = "xxx@qq.com"
mail_host = "smtp.163.com"
mail_user = "yyy"
mail_password = "zzz"
mail_postfix = "163.com"

def send_mail(to_list, sub, content):
	me = "zm" + "<" + mail_user + "@" + mail_postfix + ">"
	msg = MIMEText(content, _subtype = 'plain', _charset = 'gb2312')
	msg['Subject'] = sub
	msg['From'] = me
	msg['to'] = ";".join(to_list)
	try:
		server = smtplib.SMTP()
		server.connect(mail_host)
		server.login(mail_user, mail_password)
		server.sendmail(me, to_list, msg.as_string())
		server.close()
		return True
	except Exception, e:
		print str(e)
		return False

if __name__ == '__main__':
	if send_mail(mailto_list, "zm", "Hello M, Please contact me immediately when you see this email."):
		print "Success"
	else:
		print "Fail"
本实例已经经过测试,只需填写适当邮件参数即可。

在测试的过程中如果遇到问题,可以根据下面网易提供的返回结果判断错误原因:

http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html


您好,要使用 Python 发送带附件的电子邮件,可以使用 Python 内置的 smtplib 和 email 模块。以下是示例代码: ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # 发件人邮箱地址 sender = 'your_email@example.com' # 收件人邮箱地址 receiver = 'recipient_email@example.com' # 邮件主题 subject = 'Email with Attachment' # 邮件正文 body = 'This email contains an attachment.' # 创建一个带附件的邮件实例 msg = MIMEMultipart() msg['From'] = sender msg['To'] = receiver msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) # 添加附件 with open('attachment.txt', 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='txt') attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt') msg.attach(attachment) # 发送邮件 try: smtp_obj = smtplib.SMTP('smtp.example.com', 587) smtp_obj.starttls() smtp_obj.login(sender, 'password') smtp_obj.sendmail(sender, receiver, msg.as_string()) print('Email with attachment sent successfully!') except Exception as e: print('Error sending email: ', e) finally: smtp_obj.quit() ``` 在上面的代码中,您需要将 `sender` 和 `receiver` 变量替换为实际的电子邮件地址,将 `subject` 和 `body` 变量设置为您想要的主题和正文内容。您还需要将 `smtp_obj` 变量中的 SMTP 服务器地址和端口号替换为您的实际值,并将 `sender` 和 `password` 替换为您的实际发件人电子邮件地址和密码。最后,您需要将附件的文件名和路径替换为您的实际附件文件名和路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值