e-mail ideas (borrowing from third-party services):
1, Simulation server , including: Server address, sender address, sender's password
2. Create an instance with an attachment:1, create a massage 2, massage including the sender's address, the recipient's address, title
3, the body to the text mode,mimetext function, Its parameters are: the contents of the message or files (documents, videos, pictures, which you have to read the file to send), the format of the message, Utf-8
4, Add the body: with the Attach function, you can use multiple attach functions to pass the file
5, E -mail: Enter the server (login)login( login function ),send sendmail( send ), The required parameters are: sent address, receiver,message.as_string ()
Import Smtplib
from Email.mime.text import Mimetext
from Email.mime.multipart import Mimemultipart
from Email.header import Header
#模拟服务器
#SMTP服务器
smtpserver= "smtp.163.com"
#发邮件的地址
sender= " xxxx @163.com "
#发送者邮件的授权密码
passwd= " xxxxx "
# Create an instance with attachments
message = Mimemultipart ()
message[ ' from ' ] = Sender
message[ ' to ' ] = " xxxx @qq. com"
subject = ' Python SMTP mail test '
message[ ' subject ' ] = Subject
# message body content
Message.attach (Mimetext ( ' This is the rookie tutorial Python Mail sending test ... ' , ' Plain ' , ' Utf-8 ' )
# Construction attachment 1
ATT1 = Mimetext (open (' filename ', ' RB '). Read (), ' base64 ', ' Utf-8 ')
att1["Content-type"] = ' Application/octet-stream '
# filename Here can be arbitrarily written, what name to write, what name is displayed in the message
att1["Content-disposition"] = ' attachment; filename= ' file name '
Message.attach (ATT1)
# Construction Attachment 2
ATT2 = Mimetext (Open ('file name',' RB '). Read (),' base64 ',' Utf-8 ')
att2["Content-type"] =' Application/octet-stream '
att2["Content-disposition"] =' attachment; filename= 'file name"'
Message.attach (ATT2)
Try:
MailServer = Smtplib. SMTP (SmtpServer, 25)# 25 is the port number (mail), 0-1024 is occupied by the system
# Login Mailbox
Mailserver.login (Sender, passwd)# What you need is the address of the mailbox and the authorization password
# Send File
Mailserver.sendmail (Sender, ["xxxx@qq. com "], message.as_string ())
Print"Mail sent successfully")
exceptSmtplib. Smtpexception:
Print"Error: Unable to send mail")
Python route: Send mail with file attached