📜  如何在Python自动发送电子邮件

📅  最后修改于: 2022-05-13 01:54:46.875000             🧑  作者: Mango

如何在Python自动发送电子邮件

在本文中,我们将了解如何发送自动电子邮件,其中包括发送文本消息、重要照片和重要文件等。在Python。

为此,我们将使用两个库:email 和 smtplib,以及 MIMEMultipart 对象。这个对象有多个子类;这些子类将用于构建我们的电子邮件消息。

  • MIMEText:它由简单的文本组成。这将是电子邮件的正文。
  • MIMEImage:这将允许我们将图像添加到我们的电子邮件中。
  • MIMEAudio:如果我们想添加音频文件,我们可以在这个子类的帮助下轻松完成。
  • MIMEApplication:这可用于添加任何内容或任何其他附件。

分步实施

第一步:导入以下模块

Python3
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os


Python3
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('YourMail@gmail.com', 'Your Password')


Python3
msg = MIMEMultipart()
msg['Subject'] = subject
msg.attach(MIMEText(text))


Python3
img_data = open(one_img, 'rb').read()
msg.attach(MIMEImage(img_data, 
                     name=os.path.basename(one_img)))


Python3
with open(one_attachment, 'rb') as f:
    file = MIMEApplication(
        f.read(), name=os.path.basename(one_attachment)
    )
    file['Content-Disposition'] = f'attachment; \
    filename="{os.path.basename(one_attachment)}"'
    msg.attach(file)


Python3
to = ["klm@gmail.com", "xyz@gmail.com", "abc@gmail.com"]
smtp.sendmail(from_addr="Your Login Email",
              to_addrs=to, msg=msg.as_string())
smtp.quit()


Python3
# Import the following module
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
  
# initialize connection to our
# email server, we will use gmail here
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
  
# Login with your email and password
smtp.login('Your Email', 'Your Password')
  
  
# send our email message 'msg' to our boss
def message(subject="Python Notification", 
            text="", img=None,
            attachment=None):
    
    # build message contents
    msg = MIMEMultipart()
      
    # Add Subject
    msg['Subject'] = subject  
      
    # Add text contents
    msg.attach(MIMEText(text))  
  
    # Check if we have anything
    # given in the img parameter
    if img is not None:
          
        # Check whether we have the lists of images or not!
        if type(img) is not list:  
            
              # if it isn't a list, make it one
            img = [img] 
  
        # Now iterate through our list
        for one_img in img:
            
              # read the image binary data
            img_data = open(one_img, 'rb').read()  
            # Attach the image data to MIMEMultipart
            # using MIMEImage, we add the given filename use os.basename
            msg.attach(MIMEImage(img_data,
                                 name=os.path.basename(one_img)))
  
    # We do the same for
    # attachments as we did for images
    if attachment is not None:
          
        # Check whether we have the
        # lists of attachments or not!
        if type(attachment) is not list:
            
              # if it isn't a list, make it one
            attachment = [attachment]  
  
        for one_attachment in attachment:
  
            with open(one_attachment, 'rb') as f:
                
                # Read in the attachment
                # using MIMEApplication
                file = MIMEApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
              
            # At last, Add the attachment to our message object
            msg.attach(file)
    return msg
  
  
# Call the message function
msg = message("Good!", "Hi there!",
              r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
              r"C:\Users\Dell\Desktop\slack.py")
  
# Make a list of emails, where you wanna send mail
to = ["ABC@gmail.com",
      "XYZ@gmail.com", "insaaf@gmail.com"]
  
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="hello@gmail.com",
              to_addrs=to, msg=msg.as_string())
  
 # Finally, don't forget to close the connection
smtp.quit()


Python3
import schedule
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
  
# send our email message 'msg' to our boss
def message(subject="Python Notification", 
            text="", img=None, attachment=None):
    
    # build message contents
    msg = MIMEMultipart()
      
    # Add Subject
    msg['Subject'] = subject  
      
    # Add text contents
    msg.attach(MIMEText(text))  
  
    # Check if we have anything
    # given in the img parameter
    if img is not None:
  
          # Check whether we have the
        # lists of images or not!
        if type(img) is not list:
            
              # if it isn't a list, make it one
            img = [img]  
  
        # Now iterate through our list
        for one_img in img:
            
              # read the image binary data
            img_data = open(one_img, 'rb').read()  
              
            # Attach the image data to MIMEMultipart
            # using MIMEImage,
            # we add the given filename use os.basename
            msg.attach(MIMEImage(img_data, 
                                 name=os.path.basename(one_img)))
  
    # We do the same for attachments
    # as we did for images
    if attachment is not None:
  
          # Check whether we have the
        # lists of attachments or not!
        if type(attachment) is not list:
            
              # if it isn't a list, make it one
            attachment = [attachment]  
  
        for one_attachment in attachment:
  
            with open(one_attachment, 'rb') as f:
                
                # Read in the attachment using MIMEApplication
                file = MIMEApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
              
            # At last, Add the attachment to our message object
            msg.attach(file)
    return msg
  
  
def mail():
    
    # initialize connection to our email server,
    # we will use gmail here
    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
      
    # Login with your email and password
    smtp.login('Email', 'Password')
  
    # Call the message function
    msg = message("Good!", "Hi there!",
                  r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
                  r"C:\Users\Dell\Desktop\slack.py")
      
    # Make a list of emails, where you wanna send mail
    to = ["ABC@gmail.com",
          "XYZ@gmail.com", "insaaf@gmail.com"]
  
    # Provide some data to the sendmail function!
    smtp.sendmail(from_addr="hello@gmail.com",
                  to_addrs=to, msg=msg.as_string())
      
    # Finally, don't forget to close the connection
    smtp.quit()  
  
  
schedule.every(2).seconds.do(mail)
schedule.every(10).minutes.do(mail)
schedule.every().hour.do(mail)
schedule.every().day.at("10:30").do(mail)
schedule.every(5).to(10).minutes.do(mail)
schedule.every().monday.do(mail)
schedule.every().wednesday.at("13:15").do(mail)
schedule.every().minute.at(":17").do(mail)
  
while True:
    schedule.run_pending()
    time.sleep(1)


第 2 步:让我们建立与电子邮件服务器的连接。



  • 提供服务器地址和端口号以启动我们的SMTP连接
  • 然后我们将使用smtpehlo发送EHLO (扩展问候)命令。
  • 现在,我们将使用smtpstarttls以启用传输层安全性 ( TLS ) 加密。

蟒蛇3

smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('YourMail@gmail.com', 'Your Password')

第 3 步:现在,构建消息内容。

  • 初始化后将 MIMEMultipart对象分配给 msg 变量。
  • MIMEText函数将用于附加文本。

蟒蛇3

msg = MIMEMultipart()
msg['Subject'] = subject
msg.attach(MIMEText(text))

第4步:我们来看看如何附加图片和多个附件。

附上图片:

  • 首先,将图像作为二进制数据读取。
  • 使用MIMEImage将图像数据附加到MIMEMultipart ,我们添加给定的文件名 use os基名

蟒蛇3

img_data = open(one_img, 'rb').read()
msg.attach(MIMEImage(img_data, 
                     name=os.path.basename(one_img)))

附加几个文件:

  • 使用MIMEApplication阅读附件。
  • 然后我们编辑附加的文件元数据。
  • 最后,将附件添加到我们的消息对象中。

蟒蛇3



with open(one_attachment, 'rb') as f:
    file = MIMEApplication(
        f.read(), name=os.path.basename(one_attachment)
    )
    file['Content-Disposition'] = f'attachment; \
    filename="{os.path.basename(one_attachment)}"'
    msg.attach(file)

第 5 步:最后一步是发送电子邮件。

  • 列出您要发送的所有电子邮件。
  • 然后,通过使用sendmail函数,传递from where、to where、邮件内容等参数。
  • 最后,只需退出服务器连接。

蟒蛇3

to = ["klm@gmail.com", "xyz@gmail.com", "abc@gmail.com"]
smtp.sendmail(from_addr="Your Login Email",
              to_addrs=to, msg=msg.as_string())
smtp.quit()

下面是完整的实现:

蟒蛇3

# Import the following module
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
  
# initialize connection to our
# email server, we will use gmail here
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
  
# Login with your email and password
smtp.login('Your Email', 'Your Password')
  
  
# send our email message 'msg' to our boss
def message(subject="Python Notification", 
            text="", img=None,
            attachment=None):
    
    # build message contents
    msg = MIMEMultipart()
      
    # Add Subject
    msg['Subject'] = subject  
      
    # Add text contents
    msg.attach(MIMEText(text))  
  
    # Check if we have anything
    # given in the img parameter
    if img is not None:
          
        # Check whether we have the lists of images or not!
        if type(img) is not list:  
            
              # if it isn't a list, make it one
            img = [img] 
  
        # Now iterate through our list
        for one_img in img:
            
              # read the image binary data
            img_data = open(one_img, 'rb').read()  
            # Attach the image data to MIMEMultipart
            # using MIMEImage, we add the given filename use os.basename
            msg.attach(MIMEImage(img_data,
                                 name=os.path.basename(one_img)))
  
    # We do the same for
    # attachments as we did for images
    if attachment is not None:
          
        # Check whether we have the
        # lists of attachments or not!
        if type(attachment) is not list:
            
              # if it isn't a list, make it one
            attachment = [attachment]  
  
        for one_attachment in attachment:
  
            with open(one_attachment, 'rb') as f:
                
                # Read in the attachment
                # using MIMEApplication
                file = MIMEApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
              
            # At last, Add the attachment to our message object
            msg.attach(file)
    return msg
  
  
# Call the message function
msg = message("Good!", "Hi there!",
              r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
              r"C:\Users\Dell\Desktop\slack.py")
  
# Make a list of emails, where you wanna send mail
to = ["ABC@gmail.com",
      "XYZ@gmail.com", "insaaf@gmail.com"]
  
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="hello@gmail.com",
              to_addrs=to, msg=msg.as_string())
  
 # Finally, don't forget to close the connection
smtp.quit()

输出:

安排电子邮件

为了安排邮件,我们将使用Python中的schedule包。它非常轻巧且易于使用。

安装模块

pip install schedule

现在看看在schedule模块中定义的不同函数及其用途:

下面的函数将每 2 秒调用一次函数mail。

schedule.every(2).seconds.do(mail) 

这将每 10 分钟调用一次函数邮件。



schedule.every(10).minutes.do(mail)

这将每小时调用该函数。

schedule.every().hour.do(mail)

每天上午 10:30 打电话。

schedule.every().day.at("10:30").do(mail)

打电话给特定的一天。

schedule.every().monday.do(mail)

下面是实现:

蟒蛇3

import schedule
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
  
# send our email message 'msg' to our boss
def message(subject="Python Notification", 
            text="", img=None, attachment=None):
    
    # build message contents
    msg = MIMEMultipart()
      
    # Add Subject
    msg['Subject'] = subject  
      
    # Add text contents
    msg.attach(MIMEText(text))  
  
    # Check if we have anything
    # given in the img parameter
    if img is not None:
  
          # Check whether we have the
        # lists of images or not!
        if type(img) is not list:
            
              # if it isn't a list, make it one
            img = [img]  
  
        # Now iterate through our list
        for one_img in img:
            
              # read the image binary data
            img_data = open(one_img, 'rb').read()  
              
            # Attach the image data to MIMEMultipart
            # using MIMEImage,
            # we add the given filename use os.basename
            msg.attach(MIMEImage(img_data, 
                                 name=os.path.basename(one_img)))
  
    # We do the same for attachments
    # as we did for images
    if attachment is not None:
  
          # Check whether we have the
        # lists of attachments or not!
        if type(attachment) is not list:
            
              # if it isn't a list, make it one
            attachment = [attachment]  
  
        for one_attachment in attachment:
  
            with open(one_attachment, 'rb') as f:
                
                # Read in the attachment using MIMEApplication
                file = MIMEApplication(
                    f.read(),
                    name=os.path.basename(one_attachment)
                )
            file['Content-Disposition'] = f'attachment;\
            filename="{os.path.basename(one_attachment)}"'
              
            # At last, Add the attachment to our message object
            msg.attach(file)
    return msg
  
  
def mail():
    
    # initialize connection to our email server,
    # we will use gmail here
    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.ehlo()
    smtp.starttls()
      
    # Login with your email and password
    smtp.login('Email', 'Password')
  
    # Call the message function
    msg = message("Good!", "Hi there!",
                  r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
                  r"C:\Users\Dell\Desktop\slack.py")
      
    # Make a list of emails, where you wanna send mail
    to = ["ABC@gmail.com",
          "XYZ@gmail.com", "insaaf@gmail.com"]
  
    # Provide some data to the sendmail function!
    smtp.sendmail(from_addr="hello@gmail.com",
                  to_addrs=to, msg=msg.as_string())
      
    # Finally, don't forget to close the connection
    smtp.quit()  
  
  
schedule.every(2).seconds.do(mail)
schedule.every(10).minutes.do(mail)
schedule.every().hour.do(mail)
schedule.every().day.at("10:30").do(mail)
schedule.every(5).to(10).minutes.do(mail)
schedule.every().monday.do(mail)
schedule.every().wednesday.at("13:15").do(mail)
schedule.every().minute.at(":17").do(mail)
  
while True:
    schedule.run_pending()
    time.sleep(1)

输出: