python发邮件详解_python实现发送邮件详解

[Python]代码

#_*_encoding:utf-8_*_

#script for python3.2

#-------------------------------------------------------------------------------

# Name: 发送邮件

# Purpose:

#

# Author: QiuChangJie

#

# Created: 10/09/2012

# Copyright: (c) cj.qiu 2012

# Licence:

#-------------------------------------------------------------------------------

import os

import smtplib

import mimetypes

from email.mime.multipart import MIMEMultipart

from email.mime.base import MIMEBase

from email.mime.text import MIMEText

from email.mime.audio import MIMEAudio

from email.mime.image import MIMEImage

from email.encoders import encode_base64

MAIL_163_USER = "[email protected]"

MAIL_163_PWD = "test"

MAIL_YEAH_USER = "[email protected]"

MAIL_YEAH_PWD = "test"

MAIL_GOOGLE_HOST = "smtp.gmail.com"

MAIL_163_HOST = "smtp.163.com"

MAIL_YEAH_HOST = "smtp.yeah.com"

RECIPIENT = ["[email protected]"]

ATTACHMENTS = []

class QMail():

def __init__(self, user, pwd, host):

self.mail_user = user

self.mail_pwd = pwd

self.mail_server = smtplib.SMTP()

self.mail_server.connect(host)

self.mail_server.ehlo()

self.mail_server.starttls()

self.mail_server.ehlo()

self.mail_server.login(self.mail_user, self.mail_pwd)

def __del__(self):

self.mail_server.close()

def send_mail(self, recipient, subject, text, att_files=[]):

msg = MIMEMultipart()

msg["From"] = self.mail_user

msg["Subject"] = subject

msg["To"] = ",".join(recipient)

msg.attach(MIMEText(text))

if len(att_files) > 0:

for file_name in att_files:

msg.attach(self.get_attachment(file_name))

self.mail_server.sendmail(self.mail_user, recipient, msg.as_string())

def get_attachment(self, file_name):

content_type, encoding = mimetypes.guess_type(file_name)

if content_type is None or encoding is not None:

content_type = "application/octet-stream"

main_type, sub_type = content_type.split('/', 1)

file = open(file_name, "rb")

if main_type == "text":

attachment = MIMEText(file.read())

elif main_type == 'message':

attachment = email.message_from_file(file)

elif main_type == 'image':

attachment = MIMEImage(file.read(), _subType=sub_type)

elif main_type == 'audio':

attachment = MIMEAudio(file.read(), _subType=sub_type)

else:

attachment = MIMEBase(main_type, sub_type)

attachment.set_payload(file.read())

encode_base64(attachment)

file.close()

attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name))

return attachment

def test():

mail = QMail("[email protected]", "test", MAIL_163_HOST)

mail.send_mail(["[email protected]"], "sub_test", "text_test", r"G:\WorkSpace\Doing\CMMI文档模板.dot")

if __name__ == '__main__':

test()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值