Skip to content

Add script to send emails via gmail #1014

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

Merged
merged 1 commit into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions gmail_automation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Automated Gmail sender

## Key features
- Secure SMTP connection using TLS
- Support for attachments
- Error handling
- Easy to integrate into other Python programs
- Object-oriented design for re-usability

## Setup instructions

To use this script, you'll need to follow these steps:

1. First, set up Google App Password:
- Go to your Google Account settings
- Navigate to Security > 2-Step Verification
- At the bottom, click on "App passwords"
- Generate a new app password for your Python script
- Save this password safely (you'll only see it once)

Note:
In https://myaccount.google.com/security, do you see 2-step verification set to ON? If yes, then visiting https://myaccount.google.com/apppasswords should allow you to set up application specific passwords.

2. Install "secure-smtplib"
```
pip install secure-smtplib
```

Use the script
```
# Create the sender object
sender = GmailSender("[email protected]", "your-app-password")

sender.send_email(
to_email="[email protected]",
subject="Hello!",
body="This is an automated email."
)

# Use the below script to send the email via attachments
sender.send_email(
to_email="[email protected]",
subject="Report",
body="Please find the attached report.",
attachments=["report.pdf", "data.xlsx"]
)
```

## Author
Mihir Deshpande

## Important security notes:
- Never share your app password
- Don't commit the script with your credentials
- Consider using environment variables for sensitive data
1 change: 1 addition & 0 deletions gmail_automation/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
secure-smtplib==0.1.1
69 changes: 69 additions & 0 deletions gmail_automation/sender.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os


class GmailSender:
def __init__(self, sender_email, app_password):
self.sender_email = sender_email
self.app_password = app_password
self.smtp_server = "smtp.gmail.com"
self.smtp_port = 587

def create_message(self, to_email, subject, body, attachments=None):
message = MIMEMultipart()
message["From"] = self.sender_email
message["To"] = to_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
if attachments:
for file_path in attachments:
if os.path.exists(file_path):
with open(file_path, "rb") as file:
attachment = MIMEApplication(file.read(), _subtype="txt")
attachment.add_header(
"Content-Disposition",
"attachment",
filename=os.path.basename(file_path)
)
message.attach(attachment)

return message

def send_email(self, to_email, subject, body, attachments=None):
"""
Send an email through Gmail.

Args:
to_email (str): Recipient's email address
subject (str): Email subject
body (str): Email body content
attachments (list): List of file paths to attach (optional)
"""
try:
message = self.create_message(to_email, subject, body, attachments)
with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
server.starttls()
server.login(self.sender_email, self.app_password)
server.send_message(message)

print(f"Email sent successfully to {to_email}")
return True

except Exception as e:
print(f"Error sending email: {str(e)}")
return False


if __name__ == "__main__":
SENDER_EMAIL = "[email protected]"
APP_PASSWORD = "<app-password>" # Generate this from Google Account settings
gmail_sender = GmailSender(SENDER_EMAIL, APP_PASSWORD)
gmail_sender.send_email(
to_email="[email protected]",
subject="Test Email",
body="Adios!",
attachments=["path/to/file.txt"] # Optional
)
Loading