Python3 自制 sendmail 脚本

需要调用的库:

import sys
import smtplib
from email.mime.text  import  MIMEText
from  email.header import  Header

这里使用的是QQ邮件:smtp.qq.com

QQ邮箱需要注册一段时间才可以使用smtp服务

需要准备的变量:

receiver = sys.argv[1]
From = sys.argv[2]
To = sys.argv[3]
subject = sys.argv[4]

为了便捷调用所以使用sys.argv直接传参,而不是交互或固定式

sys.argv[1] #传入的第一个参数,类似于bash中的$1

$1=收件人,$2=发送者 $3=收件人姓名 $4=标题

完整代码:

#发送邮件脚本 $1=收件人,$2=发送者 $3=收件人姓名 $4=标题
import sys
import smtplib
from email.mime.text  import  MIMEText
from  email.header import  Header



receiver = sys.argv[1]
From = sys.argv[2]
To = sys.argv[3]
subject = sys.argv[4]


def config(sender='xxxx@qq.com', receiver = 'None', From='None', To='None', Subject='None'):
    sender = 'xxxxx@qq.com'
    receiver = '%s'%receiver
    msg = MIMEText("您好。<br><br><br><br>"
                   "<br> <br>"

                   "xx技术股份有限公司 <br>"
                   "手机: xx<br>"
                   "座机:xxx<br>"
                   "邮箱:xxxx@xx.com<br>"
                   "地址:xxxx<br>"
                   "邮编:xxxx<br>"
                   "===================================<br>"
                   "", 'HTML', 'utf-8')
    msg['From'] = Header('%s'%From, 'utf-8')
    msg['To'] = Header('%s'%To, 'utf-8')
    msg['Subject'] = Header('%s'%Subject, 'utf-8')
    sendm(sender, receiver, msg)





def sendm(sender, receiver, msg):
    try:
        smtp = smtplib.SMTP()
        smtp.connect('smtp.qq.com')
        smtp.login('xxxxxx@qq.com', 'SMTP授权码')
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        print('邮件发送成功!\n%s'%sender)
    except:
        print('发送失败!\n%s'%sender)


if __name__ == '__main__':
    config(receiver=receiver, From=From, To=To, Subject=subject)

smtp.login(‘xxxxxx@qq.com’, ‘SMTP授权码’) #第二个变量为QQ邮箱的授权码

调用脚本

即可

发表评论

电子邮件地址不会被公开。 必填项已用*标注