1.引入第三方模块

下载连接:https://pypi.org/project/yagmail/#files

python发送邮件功能

2.安装方式:

pip install yagmail-0.10.212-py2.py3-none-any.whl

说明:存在中文乱码的问题

3.设置邮箱

1)启动POP3/SMTP服务

2)设置授权码

python发送邮件功能

4.编写脚本,如下图所示

python发送邮件功能

5.方法解析

1)mail = yagmail.SMTP()  #实际就是类的实例化

类的构造函数如下所示,详细的函数,请自行导入模块进行查看

class SMTP():
    """ :class:`yagmail.SMTP` is a magic wrapper around
    ``smtplib``'s SMTP connection, and allows messages to be sent."""

    def __init__(self, user=None, password=None, host='smtp.gmail.com', port=None,
                 smtp_starttls=None, smtp_ssl=True, smtp_set_debuglevel=0,
                 smtp_skip_login=False, encoding="utf-8", oauth2_file=None,
                 soft_email_validation=True, **kwargs):
        self.log = get_logger()
        self.set_logging()
        if smtp_skip_login and user is None:
            user = ''
        elif user is None:
            user = self._find_user_home_path()
        self.user, self.useralias = self._make_addr_alias_user(user)
        self.soft_email_validation = soft_email_validation
        if soft_email_validation:
            validate_email_with_regex(self.user)
        self.is_closed = None
        self.host = host
        self.port = str(port) if port is not None else '465' if smtp_ssl else '587'
        self.smtp_starttls = smtp_starttls
        self.ssl = smtp_ssl
        self.smtp_skip_login = smtp_skip_login
        self.debuglevel = smtp_set_debuglevel
        self.encoding = encoding
        self.kwargs = kwargs
        if oauth2_file is not None:
            self.login_oauth2(oauth2_file)
        else:
            self.login(password)
        self.cache = {}
        self.unsent = []
        self.log.info('Connected to SMTP @ %s:%s as %s', self.host, self.port, self.user)
        self.num_mail_sent = 0



2)mail.send ()   #实例化对象调用send方法,通过此方法发送邮件

send()函数如下所示:

def send(self, to=None, subject=None, contents=None, attachments=None, cc=None, bcc=None,
         preview_only=False, headers=None):
    """ Use this to send an email with gmail"""
    addresses = self._resolve_addresses(to, cc, bcc)
    if not addresses['recipients']:
        return {}
    msg = self._prepare_message(addresses, subject, contents, attachments, headers)

    if preview_only:
        return addresses, msg.as_string()
    return self._attempt_send(addresses['recipients'], msg.as_string())



相关文章:

  • 2022-12-23
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-11
  • 2022-03-09
  • 2021-07-09
  • 2021-10-22
  • 2022-12-23
  • 2022-01-15
相关资源
相似解决方案