用python发邮件(段落与文字)

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 自定义发送邮件的函数
'''
    配置发邮件所需的基础信息
    my_sender    # 配置发件人邮箱地址
    my_pass      # 配置发件人邮箱密码
    to_user      # 配置收件人邮箱地址
    my_nick      # 配置发件人昵称
    to_nick      # 配置收件人昵称
    mail_msg     # 配置邮件内容

'''

def mail(my_sender,my_pass,to_user,my_nick,to_nick,mail_msg):
# 必须将邮件内容做一次MIME的转换 -- 这是发送含链接的邮件
    msg=MIMEText(mail_msg,'html','utf-8')
# 配置发件人名称和邮箱地址
    msg['From']=formataddr([my_nick,my_sender])
# 配置收件件人名称和邮箱地址
    msg['To']=formataddr([to_nick,to_user])
# 配置邮件主题(标题)
    msg['Subject']="发送邮件测试"
# 配置Python与邮件的SMTP服务器的连接通道(如果不是QQ邮箱,SMTP服务器是需要修改的)
    server=smtplib.SMTP_SSL("smtp.qq.com", 465)
# 模拟登陆
    server.login(my_sender, my_pass)
# 邮件内容的发送
    server.sendmail(my_sender,[to_user,],msg.as_string())
# 关闭连接通道
    server.quit()
    
try:
    mail_msg = """
    

你好

请问你是哪位呢,我不太知道你是?

"""
# 调用函数(登录密码需要换成你自己的) mail('[email protected]','zkbhejnisnfzjfgfshwy','[email protected]','是哪位呢','是哪位呢',mail_msg) print('邮件发送成功!') except: print('邮件发送失败!') #打印结果:邮件发送成功! #二、 #!/usr/bin/env python3 import smtplib from email.mime.text import MIMEText SMTP_SERVER = 'smtp.qq.com' SMTP_PORT = 25 def send_mail(user,passwd,to,subject,text): msg = MIMEText(text) msg['From'] = user # 构建msg对象的发件人 msg['to'] = to # 构建msg对象的收件人 msg['Subject'] = subject # 构建msg对象的邮件正文 smtp_server = smtplib.SMTP(SMTP_SERVER,SMTP_PORT) print('Connecting To mail Server') try: smtp_server.ehlo() print('Starting Encrypted Session.') smtp_server.starttls() smtp_server.ehlo() print('Loggin Into Mail Server.') smtp_server.login(user,passwd) print('Send mail.') smtp_server.sendmail(user,to,msg.as_string()) # 利用msg的as_string()方法转换成字符串 except Exception as err: print('Sending Mail Failed:{0}'.format(err)) finally: smtp_server.quit() def main(): send_mail('[email protected]','zkbhejnisnfzjfgfshwy','[email protected]','test','''

你好

请问你是哪位呢,我不太知道你是?

'''
) if __name__ == '__main__': main() #打印结果: #Connecting To mail Server #Starting Encrypted Session. #Loggin Into Mail Server. #Send mail.

你可能感兴趣的:(用python发邮件(段落与文字))