首页 > 解决方案 > python上的SMTP utf-8错误

问题描述

首先,我不擅长英语,所以如果你了解我的英语技能,我会感谢你的。我曾尝试使用谷歌的 SMTP 发送电子邮件。但是我遇到了一些关于 utf-8 的问题。我试图找到解决方案,但我失败了。帮助我找到解决方案。

这是我的代码。

# -*- coding: utf-8 -*-

def send_with_gmail(body):
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    gmail_user = 'ychu1235@gmail.com'  # 실제 google 로그인할 때 쓰는 ID
    gmail_pw = 'This is hide security'    # 실제 google 로그인할 때 쓰는 Password

    from_addr = 'ychu1235@gmail.com'   # 보내는 사람 주소
    to_addr = 'ychu123@naver.com'      # 받는 사람 주소

    msg=MIMEMultipart('alternative')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = 'Send email with Gmail'     # 제목
    msg.attach(MIMEText(body, 'plain', 'utf-8')) # 내용 인코딩

    ########################
    # https://www.google.com/settings/security/lesssecureapps
    # Make sure less_secure_apps select 'use'
    ########################
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pw)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        print('successfully sent the mail')
    except BaseException as e:
        print("failed to send mail", str(e))

if __name__ == '__main__':
    send_msg = '''
    multi
    L
    I
    N
    E
    '''
    send_with_gmail(send_msg)

我得到了这个输出。 failed to send mail 'utf-8' codec can't decode byte 0xb0 in position 0: invalid start byte

标签: pythonemailsmtp

解决方案


推荐阅读