The ability to send mail with attachments with Python

Source: Internet
Author: User

In a Linux system, messages can be sent with the Mail command, but when sent with an attachment, the attachment is always reported as too large an error. Without knowing how to configure Linux mail, I chose Python for sending messages with attachments.

Import Smtplib

From Email.mime.multipart import Mimemultipart

From Email.mime.text import Mimetext

From email.mime.application import mimeapplication

Mail_host= "Smtp.exmail.qq.com" #设置服务器

Mail_user= "#填写用户名" #用户名

mail_pass= "#用户名对应的密码" #口令

mail_postfix= "#发件箱的后缀" #发件箱的后缀

#定义发送邮件的收件人, message headers, message contents, attachments

def send_mail (to_list,sub,content,files):

msg = Mimemultipart (_subtype= ' plain ', _charset= ' utf-8 ')

msg[' Subject ' = Sub

Msg[' from '] = Mail_user

Msg[' to '] = ";". Join (To_list)

Part=mimetext (content,_subtype= ' plain ', _charset= ' utf-8 ')

Msg.attach (part)

For file_name in Files:

Part = mimeapplication (open (file_name, ' RB '). Read ())

Part.add_header (' content-disposition ', ' attachment ', filename=file_name)

Msg.attach (part)

Server = Smtplib. SMTP ()

Server.connect (Mail_host)

Server.login (Mail_user,mail_pass)

Server.sendmail (Mail_user, To_list, msg.as_string ())

Server.close ()

Return True

mailto_list=[' recipient 1', ' Recipient 2']

files=[' file_name ',......]

Send_mail (Mailto_list, "Mail Header", "Message body", files)


This article is from the "three countries Cold jokes" blog, please be sure to keep this source http://myhwj.blog.51cto.com/9763975/1856596

The ability to send mail with attachments with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.