python socket发送邮件

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

#第三方smtp配置此处为QQ邮箱的
mail_host = 'smtp.qq.com'
#用户名
mail_user = 'xxxxx'
#密码或者授权码
mail_pass = 'xxxx'

#发送的邮箱
senderEmail = 'xxxx@qq.com'
#接收的邮箱
toEmail = ['xxxx@qq.com']
#host
HOST = 'localhost'
def sendMessage(eTitle, mSubject, eFrom, eTo) :
    message = MIMEText(mSubject, 'plain', 'utf-8')
    message['From'] = Header(eFrom, 'utf-8')
    message['To'] = Header(eTo, 'utf-8')
    message['Subject'] = Header(eTitle, 'utf-8')
    return message.as_string()

try :
    #用sendemai发送
    # smtpObj = smtplib.SMTP(HOST)
    # message = sendMessage('Test', '测试一下...', 'fromName', 'toName')
    # smtpObj.sendmail(senderEmail, toEmail, message)
    #用QQ邮箱发送
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user, mail_pass)
    message = sendMessage('wangzhenTitle','wangzehnaa','wangzhen',toEmail[0])
    smtpObj.sendmail(senderEmail, toEmail, message)
    print('发送成功')
except smtplib.SMTPException as e:
    print('Erro;无法发送邮件{}'.format(e))

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,使用socket模块可以创建网络应用程序,包括发送和接收电子邮件。SMTP(Simple Mail Transfer Protocol)是用于发送邮件的标准协议,而POP3(Post Office Protocol version 3)或IMAP4(Internet Message Access Protocol version 4)则用于接收邮件。以下是一个简单的示例,展示了如何使用Pythonsocket模块以及内置的smtp和poplib模块来发送和接收电子邮件: 发送邮件(SMTP): ```python import smtplib from email.mime.text import MIMEText # 发件人、收件人、邮件主题和正文 sender = 'your_email@example.com' receiver = 'recipient_email@example.com' subject = 'Test Email' body = 'This is a test message using Python sockets.' # 创建邮件对象 msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver # 连接SMTP服务器 smtp_server = 'smtp.example.com' # 根据实际邮件服务提供商替换 smtp_port = 587 # 或者465 for SSL/TLS smtp_conn = smtplib.SMTP(smtp_server, smtp_port) # 登录邮箱 smtp_conn.starttls() # 如果需要加密 smtp_conn.login(sender, 'your_password') # 用邮箱密码登录 # 发送邮件 smtp_conn.send_message(msg) smtp_conn.quit() ``` 接收邮件(POP3或IMAP4): ```python import poplib from email.header import decode_header # 连接POP3服务器 pop_server = 'pop.example.com' # 根据实际邮件服务提供商替换 pop_port = 995 # 或者110 for plain text mode pop_conn = poplib.POP3_SSL(pop_server, pop_port) pop_conn.user('your_username') # 登录用户名 pop_conn.pass_('your_password') # 登录密码 # 检查邮件数量和最近的邮件ID num_messages, _, _ = pop_conn.stat() last_email_id = num_messages - 1 # 取出邮件 email_data = pop_conn.retr(last_email_id) # 解码邮件内容 decoded_msg = email_data decoded_msg = decode_header(decoded_msg) # 打印邮件内容 print(f"Subject: {decoded_msg[0]}") print(f"Body: {decoded_msg}") # 关闭连接 pop_conn.quit() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值