|
| 1 | +import smtplib |
| 2 | +from email.mime.text import MIMEText |
| 3 | +from email.mime.multipart import MIMEMultipart |
| 4 | +from email.mime.application import MIMEApplication |
| 5 | +import os |
| 6 | + |
| 7 | + |
| 8 | +class GmailSender: |
| 9 | + def __init__(self, sender_email, app_password): |
| 10 | + self.sender_email = sender_email |
| 11 | + self.app_password = app_password |
| 12 | + self.smtp_server = "smtp.gmail.com" |
| 13 | + self.smtp_port = 587 |
| 14 | + |
| 15 | + def create_message(self, to_email, subject, body, attachments=None): |
| 16 | + message = MIMEMultipart() |
| 17 | + message["From"] = self.sender_email |
| 18 | + message["To"] = to_email |
| 19 | + message["Subject"] = subject |
| 20 | + message.attach(MIMEText(body, "plain")) |
| 21 | + if attachments: |
| 22 | + for file_path in attachments: |
| 23 | + if os.path.exists(file_path): |
| 24 | + with open(file_path, "rb") as file: |
| 25 | + attachment = MIMEApplication(file.read(), _subtype="txt") |
| 26 | + attachment.add_header( |
| 27 | + "Content-Disposition", |
| 28 | + "attachment", |
| 29 | + filename=os.path.basename(file_path) |
| 30 | + ) |
| 31 | + message.attach(attachment) |
| 32 | + |
| 33 | + return message |
| 34 | + |
| 35 | + def send_email(self, to_email, subject, body, attachments=None): |
| 36 | + """ |
| 37 | + Send an email through Gmail. |
| 38 | +
|
| 39 | + Args: |
| 40 | + to_email (str): Recipient's email address |
| 41 | + subject (str): Email subject |
| 42 | + body (str): Email body content |
| 43 | + attachments (list): List of file paths to attach (optional) |
| 44 | + """ |
| 45 | + try: |
| 46 | + message = self.create_message(to_email, subject, body, attachments) |
| 47 | + with smtplib.SMTP(self.smtp_server, self.smtp_port) as server: |
| 48 | + server.starttls() |
| 49 | + server.login(self.sender_email, self.app_password) |
| 50 | + server.send_message(message) |
| 51 | + |
| 52 | + print(f"Email sent successfully to {to_email}") |
| 53 | + return True |
| 54 | + |
| 55 | + except Exception as e: |
| 56 | + print(f"Error sending email: {str(e)}") |
| 57 | + return False |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + SENDER_EMAIL = "sender-dude@gmail.com" |
| 62 | + APP_PASSWORD = "<app-password>" # Generate this from Google Account settings |
| 63 | + gmail_sender = GmailSender(SENDER_EMAIL, APP_PASSWORD) |
| 64 | + gmail_sender.send_email( |
| 65 | + to_email="receiver-dude@example.com", |
| 66 | + subject="Test Email", |
| 67 | + body="Adios!", |
| 68 | + attachments=["path/to/file.txt"] # Optional |
| 69 | + ) |
0 commit comments