Send alerts via Mail

Send alerts via Mail#

Change these values accordingly

from credentials import load_credentials, get_credential

# Load credentials from credentials.txt
load_credentials()

# ⚠️ EDIT THESE VALUES
SMTP_SERVER = 'smtp.gmail.com'  # For Gmail. Change for other providers
SMTP_PORT = 587
EMAIL_SENDER = get_credential('EMAIL_SENDER')        # From credentials.txt
EMAIL_PASSWORD = get_credential('EMAIL_PASSWORD')    # From credentials.txt
EMAIL_RECIPIENTS = [get_credential('EMAIL_RECIPIENT')]  # From credentials.txt (single recipient)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os

def send_email_with_attachment(file_path, subject, message):
    """
    Send an email with attachment
    
    Args:
        file_path: path to the file to attach
        subject: email subject
        message: email body
    """
    try:
        print(f"📧 Preparing email...")
        
        # Create the message
        msg = MIMEMultipart()
        msg['From'] = EMAIL_SENDER
        msg['To'] = ', '.join(EMAIL_RECIPIENTS)
        msg['Subject'] = subject
        
        # Add the message body
        msg.attach(MIMEText(message, 'plain'))
        
        # Add the attachment if the file exists
        if file_path and os.path.exists(file_path):
            filename = os.path.basename(file_path)
            print(f"📎 Attaching file: {filename}")
            
            with open(file_path, 'rb') as attachment:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())
            
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f'attachment; filename= {filename}')
            msg.attach(part)
        
        # Connect to SMTP server
        print(f"🔌 Connecting to {SMTP_SERVER}:{SMTP_PORT}...")
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()  # Enable encryption
        
        # Login
        print(f"🔐 Logging in as {EMAIL_SENDER}...")
        server.login(EMAIL_SENDER, EMAIL_PASSWORD)
        
        # Send email
        print(f"📤 Sending email to {len(EMAIL_RECIPIENTS)} recipients...")
        server.send_message(msg)
        server.quit()
        
        print("✅ Email sent successfully!")
        return True
        
    except FileNotFoundError:
        print(f"❌ File not found: {file_path}")
        return False
    except smtplib.SMTPAuthenticationError:
        print("❌ Authentication error. Check email and password.")
        print("💡 For Gmail, use an App Password: https://myaccount.google.com/apppasswords")
        return False
    except Exception as e:
        print(f"❌ Error sending email: {e}")
        return False
# Example usage
send_email_with_attachment(
    './bayestar.multiorder.fits,1',
    '🌊 GW Alert - New Event Detected',
    'A new gravitational wave event has been detected.\nSkymap attached.'
)

Configuration for common email providers#

Gmail:

Outlook/Hotmail:

  • SMTP Server: smtp-mail.outlook.com

  • Port: 587

Yahoo:

  • SMTP Server: smtp.mail.yahoo.com

  • Port: 587

University/Institutional providers:

  • Check your institution’s IT documentation for SMTP parameters