Python automatic mail library yagmail sample code, pythonyagmail
The step-by-step process for sending the smtplib and email modules of python is as follows:
1. Import the smtplib module to the MIMEText library for text-only mail templates.
2. Sending several related parameters. The sending server of each mailbox is different. In the example of "126", the baidu search server is smtp.126.com.
3. Write the subject and body of the email. The body is in HTML format.
4. Call the SMTP sending service
General mail Method
I used to implement the automated mail function in Python as follows:
Import smtplibfrom email. mime. text import MIMETextfrom email. header import Header # sending email server smtpserver = 'smtp .sina.com '# sending email user/password user = 'username @ sina.com' password = '000000' # sending email sender = 'username @ sina.com '# recipient email = 'receive @ 126.com' # subject of the sent email subject = 'python email test' # compile the HTML-type email body msg = MIMEText ('
In fact, this code is not complex. As long as you understand that you have used email to send emails, you must consider the following issues:
- Your logon email account/Password
- Recipient's email account
- Email content (subject, body, attachment)
- Email server (SMTP.xxx.com/pop3.xxx.com)
Yagmail implements mail
Yagmail can more easily implement the automatic mail function.
Github address: https://github.com/kootenpv/yagmail
Install
pip install yagmail
Simple Example
Import yagmail # link to the email server: yag = yagmail. SMTP (user = "user@126.com", password = "1234", host = 'smtp .126.com ') # mailbox body contents = ['this is the body, and here is just text http: // somedomain/image.png ', 'you can find an audio file attached. ','/local/path/song.mp3 '] # send an email: yag. send ('taaa @ 126.com ', 'subobject', contents)
There are a total of four lines of code. Is it much simpler than the above example.
Send emails to multiple users
# Send an email: yag. send (['aa @ 126.com ', 'bb @ qq.com', 'CC @ gmail.com '], 'subobject', contents)
You only need to change the email address to a list.
Send email with attachment
# Send an email: yag. send ('aaaa @ 126.com ', 'Send attachments', contents, ["d: // log.txt", "d: // baidu_img.jpg"])
You only need to add the list of attachments to be sent.
I almost cried. Where can I find such a library of conscience? Simple is a bit different from programming languages!
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.