# -*- coding: utf-8 -*-
#导入smtplib和MIMEText
import smtplib,sys
from email.mime.text import MIMEText
def send_mail(sub,content):
#############
#要发给谁,这里发给1个人
mailto_list=["wangwei03@gyyx.cn"]
#####################
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="mail.gyyx.cn"
mail_user="wangwei03@gyyx.cn"
mail_pass="123456677890"
mail_postfix="gyyx.cn"
######################
'''''
to_list:发给谁
sub:主题
content:内容
send_mail("aaa@126.com","sub","content")
'''
me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_charset='gbk')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = "".join(mailto_list)
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, mailto_list, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(u'这是python测试邮件',u'python发送邮件'):
print u'发送成功'
else:
print u'发送失败'
python发送邮件的介绍比较多,都是需要登录某个邮件服务商,有密码修改和频繁发送被限制的问题。这里介绍一下,调用本机linux自身sendmail服务发送邮件。不需要登录,发送邮件名可以是任意名字,没有限制。1. 安装:
#yum install -y sendmail
2. 启动服务:
#service sendmail start
检查服务是否加入自启行列
#chkconfig --list |grep sendmail
3 python代码:
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
import commands
def send_mail(sender, recevier, subject, html_content):
msg = MIMEText(html_content, 'html', 'utf-8')
msg["From"] = sender
msg["To"] = recevier
msg["Subject"] = subject
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
p.communicate(msg.as_string())
send_mail("sender@xxxx.com","receive1@xxxx.com,receive2@xxxx.com","title", “mail_text”)
sender@xxx.com可以是任意邮箱名
receive1@xxxx.com是收邮件的邮箱
title是邮件标题
mail_text是邮件内容
可以结合其他介绍python发邮件的资料,发出更复杂的邮件
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)