Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed the "Less Secure App Error" #1

Open
9u3 opened this issue Jul 12, 2020 · 0 comments
Open

Fixed the "Less Secure App Error" #1

9u3 opened this issue Jul 12, 2020 · 0 comments

Comments

@9u3
Copy link

9u3 commented Jul 12, 2020

I edited the code a bit to fix it.

import smtplib
import ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

class Error(Exception):
    pass

class Client:
    def __init__(self, mail, password):
        self.mail = mail
        self.password = password
        
        
    async def send(self, receiver, body, subject=None, bcc=None, attachment_bytes=None, attachment_name=None):
        sender_email = self.mail
        password = self.password

        message = MIMEMultipart()
        message["From"] = sender_email
        message["To"] = receiver
        message["Subject"] = subject if subject else "No subject"
        message["Bcc"] = bcc

        message.attach(MIMEText(body, "plain"))
        
        if attachment_name is None and attachment_bytes is not None:
            raise Error('You did not provide an attachment name for your attachment!')
            
        if attachment_name is not None and attachment_bytes is None:
            raise Error('Can not set an attachment name without an attachment!')
        
        if attachment_bytes is not None and attachment_name is not None:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment_bytes)

            encoders.encode_base64(part)

            part.add_header(
                "Content-Disposition",
                f"attachment; filename= {attachment_name}",
            )

            message.attach(part)

        text = message.as_string()

        server = smtplib.SMTP(host="smtp.gmail.com", port=587)
        server.starttls()
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant