Python发送邮件笔记

最近因需要定期处理些核查任务并发送提醒邮件,尝试过SHELL的mailx方式命令行发送邮件设置参考,又试了一下python的邮件功能,简单记录备用参考

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header


def sendDataMail(datas,strSqlCond):
    # 
    sender = '[email protected]' 
    receiver = ['[email protected]']
    subject = 'Mail Subject: '+ strSqlCond
    smtpserver = 'smtp.somewhere.com'
    username = '[email protected]'
    password = 'your_password'
    
    #msg = MIMEMultipart('related')  #('alternative')
    msg = MIMEMultipart()
    if not isinstance(subject,unicode):  
        subject = unicode(subject, 'utf-8') 
    attmsg = MIMEText( datas,'plain','utf-8' )
    msg.attach(attmsg)
    msg['From'] = sender
    msg['To'] = ','.join(receiver)
    msg['Subject'] = Header(subject, 'utf-8')  
    
    try:
        smtp = smtplib.SMTP()  
        smtp.connect(smtpserver)  
        smtp.ehlo()  
        smtp.starttls()  
        smtp.ehlo()  
        #smtp.set_debuglevel(1)  
        smtp.login(username, password)  
        smtp.sendmail(sender, receiver, msg.as_string())  
        smtp.quit()  
    except Exception, e:
        print str(e)
        return False
        
    return 0

说明:

  • 在 python2.7环境下运行正常。
  • 包装的函数因使用需要带了个参数进来合入邮件标题,用来在收到邮件的时候在邮件列表中能先做个简单区分邮件的原因,这里是个SQL查询条件。
1 个赞

发件人貌似可以伪造。。不过会被识别为spam

1 个赞

服务器资源由ZeptoVM赞助

Partners Wiki Discord