Various poses for sending messages using Python

Source: Internet
Author: User

SMTP is the protocol that sends messages, and Python's built-in support for SMTP can send plain text messages, HTML messages, and messages with attachments.


Python supports SMTP support with Smtplib and email two modules, email is responsible for structuring the mail, Smtplib is responsible for sending mail.


Smtplib. SMTP ([host[, port[, local_hostname[, timeout]])

The SMTP class constructor, which represents the connection to the SMTP server, enables you to send instructions to the SMTP server to perform related operations such as logging in and sending mail. All parameters are optional.

HOST:SMTP Server Host Name

The port of the PORT:SMTP service, default is 25;

The Smtplib module also provides the Smtp_ssl class and the Lmtp class, and their operation is basically consistent with SMTP.

Smtplib. Methods that are provided by SMTP:

Smtp.set_debuglevel (level): Sets whether to debug mode. The default is false, which is non-debug mode, which means that no debug information is output.

Smtp.connect ([host[, Port]]): Connect to the specified SMTP server. The parameters represent Smpt hosts and ports, respectively. Note: You can also specify the port number (for example: SMPT.YEAH.NET:25) in the host parameter, so there is no need to give the port parameter.

Smtp.docmd (cmd[, argstring]): Sends instructions to the SMTP server. An optional parameter, argstring, represents the parameters of the directive.

Smtp.helo ([hostname]): Use the "helo" directive to confirm the identity to the server. The equivalent of telling the SMTP server "who I am".

Smtp.has_extn (name): Determines whether the specified name exists in the server mailing list. For security reasons, the SMTP server often blocks the directive.

Smtp.verify: Determines whether the specified e-mail address exists on the server. For security reasons, the SMTP server often blocks the directive.

Smtp.login (user, password): Log on to the SMTP server. Almost all SMTP servers now have to allow messages to be sent after verifying that the user information is legitimate.

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, rcpt_options]): Send mail. Notice here that the third parameter, MSG, is a string that represents the message. We know that the mail is generally composed of the title, sender, recipient, mail content, attachments, etc., when sending mail, pay attention to the format of MSG. This format is the format defined in the SMTP protocol.

Smtp.quit (): Disconnects from the SMTP server, which is equivalent to sending a "quit" instruction. (Smtp.close () is used in many programs)



The Emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define the contents of the message is very simple. Here are some of the main uses:


Email.mime.base.MIMEBase (_maintype, _subtype, **_params): This is a base class for mime.

Email.mime.multipart.MIMEMultipart ([_subtype[, boundary[, _subparts[, a subclass of _params]]]]:mimebase, a collection of multiple MIME objects, _ The subtype default value is mixed. Boundary is the boundary of the Mimemultipart, and the default boundary is a number.

Email.mime.audio.MIMEAudio (_audiodata[, _subtype[, _encoder[, **_params]]): MIME Audio Object

Email.mime.image.MIMEImage (_imagedata[, _subtype[, _encoder[, **_params]]): MIME binary file object.

Email.mime.text.MIMEText (_text[, _subtype[, _charset]): Mime text object, where _text is the message content, _subtype message type, can be text/plain (plain text mail) , Html/plain (HTML mail), _charset encoding, can be gb2312 and so on.


Send Plain text


#-*-Coding:utf-8-*-


From Email.header Import Header

From Email.mime.text import Mimetext

Import Smtplib

Mailto_list = [' [email protected] ']


#构造邮件格式

msg = Mimetext (' Hello, send by Python ... ', ' plain ', ' utf-8 ')

msg[' Subject ' = "[Ansible send plain text mail]"

msg[' from ' = Header ("My python file", ' Utf-8 ')

receivers = ";". Join (Mailto_list)

Msg[' to '] = Header (receivers, ' utf-8 ')


#发送邮件

Mail_host = "devsmtprelay.paic.com.cn"

Sender = ""

Server = Smtplib. SMTP ()

Server.connect (Mail_host, 25)

Server.sendmail (sender, Receivers, msg.as_string ())

Server.close ()




Send an HTML message


#-*-Coding:utf-8-*-

From Email.header Import Header

From Email.mime.text import Mimetext

Import Smtplib

Mailto_list = [' [email protected] ']


#构造邮件格式

msg = Mimetext ('

msg[' Subject ' = "[Ansible send plain text mail]"

msg[' from ' = Header ("My python file", ' Utf-8 ')

receivers = ";". Join (Mailto_list)

Msg[' to '] = Header (receivers, ' utf-8 ')


#发送邮件

Mail_host = "devsmtprelay.paic.com.cn"

Sender = ""

Server = Smtplib. SMTP ()

Server.connect (Mail_host, 25)

Server.sendmail (sender, Receivers, msg.as_string ())

Server.close ()




Send message with attachment


#-*-Coding:utf-8-*-


From Email.header Import Header

From Email.mime.text import Mimetext

From email. Mimebase Import Mimebase

From Email.mime.multipart import Mimemultipart

From email import encoders

Import Smtplib


Mailto_list = [' [email protected] ']


#构造邮件格式

msg = Mimemultipart ()

Msg.attach (Mimetext (' Hello, send by Python ... ', ' plain ', ' utf-8 '))

msg[' Subject ' = "[Ansible send with attachment message]"

msg[' from ' = Header ("My python file", ' Utf-8 ')

receivers = ";". Join (Mailto_list)

Msg[' to '] = Header (receivers, ' utf-8 ')


# Adding an attachment is to add a mimebase that reads a picture from the Local:

With open ('/wls/jumpserver/ansible/pingan.png ', ' RB ') as F:

MIME = mimebase (' image ', ' png ', filename= ' pingan.png ')

# Add the necessary header information:

Mime.add_header (' content-disposition ', ' attachment ', filename= ' pingan.png ')

Mime.add_header (' Content-id ', ' <0> ')

Mime.add_header (' X-attachment-id ', ' 0 ')

# Read the contents of the attachment in:

Mime.set_payload (F.read ())

# Encoded with Base64:

Encoders.encode_base64 (MIME)

# Added to Mimemultipart:

Msg.attach (MIME)


#发送邮件

Mail_host = "mailgw2.paic.com.cn"

sender = ' [email protected] '

Server = Smtplib. SMTP ()

Server.connect (Mail_host, 25)

Server.sendmail (sender, Receivers, msg.as_string ())

Server.close ()


Send picture Body message


Link a picture address directly in an HTML message. Most mail services automatically block images with an outside chain because they don't know if they point to a malicious website.


To embed the image in the message body, we simply add the message as an attachment by sending it as an attachment, and then embed the attachment as a picture in HTML by referencing src= "cid:0". If you have multiple pictures, number them sequentially, and then refer to the different cid:x.


#-*-Coding:utf-8-*-


From Email.header Import Header

From Email.mime.text import Mimetext

From Email.mime.image import Mimeimage

From Email.mime.multipart import Mimemultipart

Import Smtplib


Mailto_list = [' [email protected] ']


#构造邮件格式

msg = Mimemultipart ()

s = "" "

<table width= "border=" 0 ">

<tr>

<td></td>

</tr>

</table></body>

"""

Msg.attach (Mimetext (S, ' html ', ' Utf-8 '))

msg[' Subject ' = "[Ansible send picture body message]"

msg[' from ' = Header ("My python file", ' Utf-8 ')

receivers = ";". Join (Mailto_list)

Msg[' to '] = Header (receivers, ' utf-8 ')



# Adding an attachment is to add a mimebase that reads a picture from the Local:

With open ('/wls/pingan.png ', ' RB ') as F:

Msgimage = Mimeimage (F.read ())

Msgimage.add_header (' Content-id ', ' Pinganxiaozhi ')


# Added to Mimemultipart:

Msg.attach (Msgimage)


#发送邮件

Mail_host = "mailgw2.paic.com.cn"

sender = ' [email protected] '

Server = Smtplib. SMTP ()

Server.connect (Mail_host, 25)

Server.sendmail (sender, Receivers, msg.as_string ())

Server.close ()


Various poses for sending messages using Python

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.