python 邮件发送

      当某段重要的代码出现错误的时候,我们希望能够发送邮件到某个特定的账户。在python中,邮件的发送简单的令人发指。当然,如果想要用邮件发送多媒体的数据,使用上可能稍微复杂点,但是这里的两段代码都是最简单的发送文本的。

      1.python自带的email模块进行发送

from email.MIMEText import MIMEText  
import smtplib  

email_conf = {
              "server":'smtp.163.com',
              "user":"send_email@163.com",
              "password":"secret"
              }

def sendEmail(email_config, recievers, subject, content):  
        strTo = ', '.join(recievers)  
        server = email_config.get('server')  
        user = email_config.get('user')  
        passwd = email_config.get('password')  
  
        emailMsg = MIMEText(content,_subtype='plain',_charset='utf-8')
        emailMsg['Subject'] = subject
        emailMsg['From'] = user
        emailMsg['To'] = strTo

        smtp = smtplib.SMTP()  
        smtp.connect(server)  
        smtp.login(user,passwd) 
        smtp.sendmail(user, recievers, emailMsg.as_string())    
        smtp.quit()  

if __name__ == "__main__":
    sendEmail(email_conf, "10000@qq.com", 'subject', 'email_content')
    print 'ok'


2.使用web.py进行邮件发送

因为web.py这个框架将邮件发送进行了进一步的包装,这里发送邮件就更简单了。总共5行代码。

import web
 
web.config.smtp_server = 'smtp.163.com'
web.config.smtp_username = 'sender_email@163.com'   #发送者的邮箱
web.config.smtp_password = 'secret'
 
web.sendmail('sender_email@163.com', 'recever_email@any.com', 'subject', 'email content')



Python邮件代发是指使用Python编程语言来发送电子邮件Python提供了一个内置的smtplib模块,可以用于与SMTP服务器进行通信,并发送电子邮件。 要使用Python发送电子邮件,首先需要导入smtplib模块,并创建一个SMTP对象。然后,通过调用SMTP对象的方法来设置SMTP服务器的地址、端口号、登录凭据等信息。接下来,可以使用SMTP对象的sendmail方法来发送邮件。 以下是一个简单的示例代码,演示了如何使用Python发送电子邮件: ```python import smtplib from email.mime.text import MIMEText def send_email(sender, receiver, subject, message): # 设置SMTP服务器地址和端口号 smtp_server = 'smtp.example.com' smtp_port = 587 # 设置登录凭据 username = 'your_username' password = 'your_password' # 创建SMTP对象 smtp_obj = smtplib.SMTP(smtp_server, smtp_port) # 发起与SMTP服务器的连接 smtp_obj.starttls() # 登录SMTP服务器 smtp_obj.login(username, password) # 创建邮件内容 email_message = MIMEText(message) email_message['From'] = sender email_message['To'] = receiver email_message['Subject'] = subject # 发送邮件 smtp_obj.sendmail(sender, receiver, email_message.as_string()) # 关闭与SMTP服务器的连接 smtp_obj.quit() # 调用函数发送邮件 send_email('sender@example.com', 'receiver@example.com', 'Hello', 'This is a test email.') ``` 请注意,上述示例代码中的SMTP服务器地址、端口号、登录凭据等信息需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值