0

I want to send a mail with gmail. But mail must specifically include an array. I need help. Message part in the code block, specifically accept text type.

If I tell specifically my goal; I have a .csv file, and I'm creating random Sub Sample from this file. Sub Sample includes 5 rows. I created an array with this random rows and I want to send this random rows which type is array.

import pandas as pd
import smtplib

data = pd.read_csv("Words1.csv")
row1 = data.sample(n=5)
A = [row1]
print(A)
email = '[email protected]'  # Your email
password = 'senderpassword'  # Your email account password
send_to_email = '[email protected]'  # Who you are sending the message to
message = 'A'  # The message in the email 

server = smtplib.SMTP('smtp.gmail.com', 587)  # Connect to the server
server.starttls()  # Use TLS
server.login(email, password)  # Login to the email server
server.sendmail(email, send_to_email, message)  # Send the email
server.quit()  # Logout of the email server

Thank you.

2
  • You need to "serialize" your array/list. There are many resources online on how to do this in python Commented Jan 6, 2020 at 13:18
  • pandas .to_csv() method with no input will return a csv string so just do A = row1.to_csv() you can see an example here Commented Jan 6, 2020 at 13:21

1 Answer 1

1

Solution;

import numpy as np
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

data = pd.read_csv("Words.csv")
row1 = data.sample(n=5)
A = [row1]
num = np.array(row1)

head = ['C1', 'C2', 'C3']
row = ['1','2','3','4','5']
df = pd.DataFrame(num, index=row, columns=head)
html = df.to_html()
print(html)

def py_mail(SUBJECT, BODY, TO, FROM):
    """With this function we send out our html email"""

    MESSAGE = MIMEMultipart('alternative')
    MESSAGE['subject'] = SUBJECT
    MESSAGE['To'] = TO
    MESSAGE['From'] = FROM

    HTML_BODY = MIMEText(BODY, 'html')
    MESSAGE.attach(HTML_BODY)


    password = "@YourPassword"
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(FROM,password)
    server.sendmail(FROM, [TO], MESSAGE.as_string())
    server.quit()

if __name__ == "__main__":
    """Executes if the script is run as main script (for testing purposes)"""

    email_content = html

    TO = '[email protected]'
    FROM ='[email protected]'

    py_mail("Test email subject", email_content, TO, FROM)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.