Home  >  Article  >  Backend Development  >  How to send emails to your own mailbox in Python

How to send emails to your own mailbox in Python

PHPz
PHPzforward
2023-05-12 15:16:152508browse

1. Reason

In daily development, we often need to monitor the status of the application, discover problems in time and take measures to solve them. Sending alarm information via email is a common implementation method.

2. Set up the SMTP server

Log in to the QQ mailbox background and click on the account

Find the "POP3/SMTP Service" and "IMAP/SMTP Service" items, click "Enable" ".

How to send emails to your own mailbox in Python

After successfully opening, you can see the authorization code. Please save this authorization code.

How to send emails to your own mailbox in Python

The general configuration for using SSL is as follows :

Receive mail server: pop.qq.com, use SSL, port number 995

Send mail server: smtp.qq.com, use SSL, port number 465 or 587

Account name: your QQ mailbox account name (if you have a VIP account or Foxmail account, the account name needs to fill in the complete email address)

Password: your QQ mailbox password

Email address: The complete email address of your QQ mailbox

3. Use python to send

Look at the source code first

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
 
# 发件人信息
sender_email = "657029702@qq.com"
sender_password = "上文申请的授权码"
 
# 收件人信息
recipient_email = "493614550@qq.com"
 
# 构造邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = "这是一封测试邮件"
 
# 添加正文
body = "这是一封测试邮件,用Python发送。"
msg.attach(MIMEText(body, 'plain'))
 
# 添加附件
with open("example.pdf", "rb") as attachment:
    part = MIMEApplication(attachment.read(), _subtype='pdf')
    part.add_header('Content-Disposition', 'attachment', filename="example.pdf")
    msg.attach(part)
 
# 发送邮件
with smtplib.SMTP_SSL('smtp.qq.com', 465) as smtp:
    smtp.login(sender_email, sender_password)
    smtp.sendmail(sender_email, recipient_email, msg.as_string())

The third-party library smtplib is used here, just install it

Added an attachment here, put example.pdf in the same directory as the script

How to send emails to your own mailbox in Python

Perfect!

5. Supplement

In addition to simply sending emails to mailboxes, Python can also send emails regularly. The following is the implementation code. I hope it will be helpful to everyone

pythonautomatic batch email script

'''''
该模块使自动发送邮件的模块
模块初始化时需要设置:
sender:发送人
reciver:接收者
smtpServer:发送人的服务器类型
password:登录命令
subject:邮件标题
datafile:数据文件
文件包含六个函数:
senderLogin():连接服务并登录服务
setSubject():设置邮件标题
SendMessage():邮件发送的信息
sendMail():发送邮件
quitMail():关闭邮件服务
run():执行登录、设置邮件标题、设置邮件发送信息、发送邮件、关闭邮件服务
'''

import smtplib
from mangerResultFile import FileManger
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class AutoMail(object):
    def __init__(self,sender,reciver,smtpServer, password,subject,datafile):
        #设置发送人
        self.sender=sender
        #设置登录密码
        self.password=password
        #设置接收者
        self.reciver=reciver
        #设置邮件标题
        self.subject=subject
        #设置附件路径
        self.datafile=datafile
        #设置发送邮件服务
        self.smtpServer=smtpServer
        #创建一个smtp实例
        self.smtp = smtplib.SMTP()
        #设置下发送信息包含的类型的信息体
        self.msgRoot =MIMEMultipart('related')
        #调用run函数运行
        self.run()
  
    #发送用户登录
    def senderLogin(self):
        #通过smtp实例的connect方法连接发送邮件服务
        self.smtp.connect(self.smtpServer)
        #通过smtp实例的login方法登录发送邮件服务
        self.smtp.login(self.sender,self.password)
 
    def setSubject(self):
        #设置邮件标题
        self.msgRoot['Subject']=self.subject
        
    def SendMessage(self):
        #读取附件信息到att中
        att =MIMEText(open( self.datafile, 'rb').read(), 'base64', 'utf8')
        #设置att的内容类型
        att["Content-Type"]= 'application/octet-stream'
        #给附件设置一个文件名
        att["Content-Disposition"]= 'attachment; '+'filename='+FileManger().getLastFile()+''
        
        self.msgRoot.attach(att)
    
    def sendMail(self):
        #发送邮件
        self.smtp.sendmail(self.sender,self.reciver,self.msgRoot .as_string())
    
    def quitMail(self):
        #退出邮件服务
        self.smtp.quit()
        
    def run(self):
        
        try:
            self.senderLogin()
            self.setSubject()
            self.SendMessage()
            self.sendMail()
            self.quitMail()

   print "send success...."
   except Exception,e:
   
   print e
   def test():
       #创建一个FileManger实例
       fm=FileManger()
       sender ='wang@163.com'
       receiver ='e.wang@163.com'
       smtpserver ='smtp.163.com'
       password =' '
       ject= 'XQL Autom excut project'
       filpath=fm.getLastFileWithPath()
      
      try:
          AutoMail(sender,receiver,smtpserver,password,ject,filpath)
         
         except Exception,e:
print e

if __name__=="__main__":
    test()

The above is the detailed content of How to send emails to your own mailbox in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete