-
-
Save amarabucotcepe/bbb958f0d2d2e9155b806939b05eb2c6 to your computer and use it in GitHub Desktop.
Script para enviar imagem embutida no email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.mime.image import MIMEImage | |
import numpy as np | |
from matplotlib import pyplot as plt | |
import io | |
import base64 | |
keys = open('.env').read().splitlines() | |
keys[0].split('=')[1] | |
def send_html_email(subject, html_content, img_data, recipient_email): | |
""" | |
Send HTML formatted email using Gmail | |
Args: | |
subject (str): Email subject | |
html_content (str): HTML content of email | |
recipient_email (str): Recipient's email address | |
""" | |
# Email credentials from environment variables | |
# sender_email = os.environ.get("GMAIL_ADDRESS") | |
# sender_password = os.environ.get("GMAIL_PASSWORD") | |
sender_email = keys[0].split('=')[1] | |
sender_password = keys[1].split('=')[1] | |
# Create multipart message | |
message = MIMEMultipart("related") | |
message["Subject"] = subject | |
message["From"] = sender_email | |
message["To"] = recipient_email | |
# # Convert HTML content | |
# html_part = MIMEText(html_content, "html") | |
# message.attach(html_part) | |
# Parte alternativa para o HTML | |
message_alternative = MIMEMultipart('alternative') | |
message.attach(message_alternative) | |
message_alternative.attach(MIMEText(html_content, 'html')) | |
img = MIMEImage(img_data) | |
img.add_header('Content-ID', '<image1>') | |
message.attach(img) | |
try: | |
# Create secure SSL/TLS connection | |
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server: | |
server.login(sender_email, sender_password) | |
server.send_message(message) | |
print(f"Email sent successfully to {recipient_email}") | |
except Exception as e: | |
print(f"Error sending email: {str(e)}") | |
# Example usage | |
if __name__ == "__main__": | |
array = np.random.random(10) | |
plt.plot(array) | |
# Save plot to memory buffer instead of file | |
buffer = io.BytesIO() | |
plt.savefig(buffer, format='png') | |
plt.close() | |
# Obter dados da imagem do buffer | |
buffer.seek(0) | |
img_data = buffer.getvalue() | |
html_content = """ | |
<html> | |
<body> | |
<h1>Hello</h1> | |
<p>This is a <b>HTML</b> email test.</p> | |
<img src="cid:image1"> | |
</body> | |
</html> | |
""" | |
# Salvar HTML para depuração (opcional) | |
with open('mail.html', 'w') as f: | |
f.write(html_content) | |
send_html_email("Test HTML Email", html_content, img_data, "recepient@gmail.com") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment