您的位置:首页 > 编程语言 > Python开发

笔记:阿里云服务器下python 配置邮箱服务

2018-01-03 16:52 363 查看
linux下发送邮件,我用的服务器是阿里云,向网易邮箱发邮件,因为阿里云ECS专有网络服务器禁用了25端口,所以改用了465

第一种方法:

test1.py

# coding:utf-8
import smtplib
import sys
from email.mime.text import MIMEText

mailto_list=['XXX@163.com']   #收件人邮箱列表
mail_user="XXX@163.com"       #用户名
mail_passwd="XXXXX"           #用户登录密码(第三方登录授权码)
mail_host="smtp.163.com"      #邮箱服务器
mail_postfix="163.com"        #邮箱后缀名

def send_mail(to_list,sub,content): #定义函数,参数为收件人,邮件主题,邮件内容
print content
me="<"+mail_user+">"

msg=MIMEText(content,'plain')
msg['Subject']=sub
msg['From']=me
msg['To']=';'.join(to_list)    #将收件人列表以“;” 形式隔开

try:
server = smtplib.SMTP_SSL()    #用的是SSL协议的邮箱smtp
server.connect(mail_host,465)  #smtp 的端口号465
print server.login(mail_user,mail_passwd)
server.sendmail(me,to_list,msg.as_string()) #SMTP对象使用sendmail 方法发送邮件 #SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
server.close()
except Exception, e:
print str(e)
return False

send_mail(mailto_list,"Long time no see",'happy new year,beautiful girl') #调用函数


第二种方法:

test2.py

#coding:utf-8
import sys
import smtplib
#import email.mime.multipart
from email.mime.text import MIMEText

server = 'smtp.163.com'
port = '465'

def send_mail(server,port,usr,pwd,msg):
smtp = smtplib.SMTP_SSL()
smtp.connect(server,port)
smtp.login(usr,pwd)
smtp.sendmail(msg['from'],msg['to'],msg.as_string())
smtp.quit()
print('email has send out successfully !')

if  __name__ == '__main__':
#   msg = email.mime.multipart.MIMEMutipart()
msg = MIMEText('beautiful girl','plain')
msg['subject'] = 'HELLO PYTHON,ITS MY FIRST MAIL TO YOU'
msg['From'] = '发件人邮箱@163.com'
msg['To'] = '收件人邮箱@163.com'
usr =  '用户名'
pwd = '密码' (第三方授权码)
content=' '.join(sys.argv[4:])

send_mail(server,port,usr,pwd,msg)


这两种方法大同小异,# python test1.py 运行此文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 邮箱