The first time it runs it sends the message right, like:
'Saldo: 100 USD'
and attach the PROFIT.csv
but when it runs for the second time it sends the message like
'Saldo: 100 USDSaldo: 100 USD'
and attach the file twice.
here is my code:
from email.mime.text import MIMEText
import smtplib
from email.mime.base import MIMEBase
from email import*
from datetime import datetime
import time
import schedule
import pandas as pd
import numpy as np
from API import trade_history,balance
global msg
msg = MIMEMultipart()
def atach(filename):
global msg
fp = open(filename, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=str(filename))
msg.attach(part)
def sendmail(text):
global msg
# setup the parameters of the message
message = 'Saldo: '+str(round(SALDO,2))+' USD'
password = "mypassword"
file1 = 'PROFIT.csv'
msg['From'] = "myemail#gmail.com"
msg['To'] = "otheremail#gmail.com"
msg['Subject'] = "subject"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
#create server
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
atach(file1)
#atach(file2)
smtp = smtplib.SMTP('smtp.gmail.com')
# Login Credentials for sending the mail
server.login(msg['From'], password)
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print('email done')
time.sleep(690)
schedule.every().day.at("07:00").do(sendmail,'sending email')
while True:
try:
msg = MIMEMultipart()
print("schedule: 07:00",str(datetime.today()).split(' ')[1])
schedule.run_pending()
time.sleep(59) # wait one minute
except:
print('#### Schedule ERROR ####')
time.sleep(59)
any other way to send a schedule message is great. I tryed to reinstanceate the MIMEMultipart() but it not worked
You just keep attaching content to the same global MIMEMultipart object. That is the reason for the bahaviour you see.
Why do you need a global variable for that? You could create a MIMEMultipart variable in the sendmail function and then send it as the second parameter to the atach (sic) function. Then you get a fresh MIMEMultipart object for each mail you send.
Related
I have to functions send_output_mail which will call process_mail to send mail to the given recipients with multiple attacthments.
Here is my code
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
import pandas as pd
server = '112.11.1.111'; port = 11
MY_ADDRESS = 'xyz#outlook.com'
from datetime import datetime
def process_email(**kwargs): # accept variable number of keyworded arguments
# get total email recipients
rcpt = []
for email in kwargs['emails']:
for i in email:
rcpt.append(i)
# set up the SMTP server
s = smtplib.SMTP(host=server, port=port)
msg = MIMEMultipart() # create a message
# setup the parameters of the message, to cc emails
msg['From'] = MY_ADDRESS
msg['To'] = ','.join(kwargs['emails'][0])
msg['Cc'] = ','.join(kwargs['emails'][1])
msg['Subject'] = kwargs['subject']
if 'attachments' in kwargs.keys():
for attachment in kwargs['attachments']:
fullpath_attactment = os.path.join(os.getcwd(),"Output_file",attachment) #will give full path of the file
with open(fullpath_attactment) as fp:
record = MIMEBase('application', 'octet-stream')
record.set_payload(fp.read())
encoders.encode_base64(record)
record.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(fullpath_attactment))
msg.attach(record)
s.sendmail(MY_ADDRESS, rcpt, msg.as_string()) **#Getting Error Here**
s.quit()
def send_output_mail():
emails = [["xyz#outlook.com", "hy#outlook.com"], ["xxx#outlook.com","yy#outlook.com"]]
subject = "Reports"
process_email(emails=emails, subject=subject, attachments= ["xx.csv","yy.csv"])
Problem
As i Debugged i am getting smtplib.SMTPDataError: (554, b'5.5.1 Error: no valid recipients') while executing line
s.sendmail(MY_ADDRESS, rcpt, msg.as_string())
I have crosschecked and the mailid that i have written and it was also correct, still getting this error.
I am trying to create an email bot that will send me a random pdf file from a folder. Though my code is not showing any error, I am not getting any mail. It'd be helpful if you can show me where I am going wrong and what should I do. Thank you.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import random
def send():
body = ""
sender_email = "email"
password = "my_password"
receiver_email = "email"
msg = MIMEMultipart()
msg['Subject'] = '[Email Test]'
msg['From'] = sender_email
msg['To'] = receiver_email
msg.attach(MIMEText(body, 'plain'))
path = "C:/Users/Asus/PycharmProjects/messenger_bot/files"
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])
attachment = open(os.path.join(path, random.choice(files)), 'rb')
payload = MIMEBase('application', 'octate-stream')
# payload = MIMEBase('application', 'pdf', Name=pdfname)
payload.set_payload(attachment.read())
# enconding the binary into base64
encoders.encode_base64(payload)
# add header with pdf name
payload.add_header('Content-Decomposition', 'attachment', filename=files)
msg.attach(payload)
# use gmail with port
session = smtplib.SMTP('smtp.gmail.com', 587)
# enable security
session.starttls()
# login with mail_id and password
session.login(sender_email, password)
text = msg.as_string()
session.sendmail(sender_email, receiver_email, text)
session.quit()
print('Mail Sent')
Are you sure that the sender email is correct?
change the sender_email from "email" to your actual email and it should work
From what I gather from official documentation. The issue you are having is because starttls takes a keyfile and a certfile together or a context by itself and you haven't given either.
try adding this:
context = ssl.create_default_context()
and then change your starttls() call to
starttls(context=context)
Im using python 2.7
Im trying to send emails to more than one person. Only one person receives not others.
My code is;
import smtplib
import time
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from utilities.ConfigReader import *
def sendEmailNotification(subject, body):
sender, receiver = getNotificationSettings()
smtpServer, smtpPort, timeout = getSMTPSettings()
msg = MIMEMultipart()
R = receiver.split(",")
body = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = receiver
msg.attach(body)
server = smtplib.SMTP(smtpServer, smtpPort)
server.ehlo()
try:
print receiver
print R
server.sendmail(sender, R, msg.as_string())
except smtplib.SMTPException:
time.sleep(float(timeout))
server.sendmail(sender, R, msg.as_string())
server.quit()
sendEmailNotification("Test","Test")
Here R prints;
['test#lob.com', 'ratha#lob.com']
receiver prints;
test#lob.com, ratha#lob.com
I followed following thread but didnt work to me;
How to send email to multiple recipients using python smtplib?
What im doing wrong here?
I figured out my issue. ratha#lob.com is in the list email test#lob.com . So I haven't received the email for ratha#lob.com , but received for test#lob.com . After changing two private emails, i receive in both emails. So code is working as expected.
I'm sending email through an account with the following Python code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def sendMail(target, subject, txt):
fromaddr = 'my#test.com'
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = target
msg['Subject'] = subject
msg.attach(MIMEText("This is my text"))
server = smtplib.SMTP('node01.mailserver.com', '587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, 'mypassword')
server.sendmail(fromaddr, target, msg.as_string())
server.quit()
This works quite well and I can receive the emails.
However, the timestamp which is displayed in my email client shows the time I downloaded the mail from the server and not time the email was actually send.
Is there a way how to correctly add the sending time to the email? I would assume that the sending time is not correctly set and that's the reason why the download time is displayed?
Or do I make other mistakes?
Thanks!
This works for me:
...
import email.utils
...
msg['Date'] = email.utils.formatdate(localtime=True)
...
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to send Email Attachments with python
I would like to edit the following code and send an email with an attachment. Attachment is a pdf file, it is under /home/myuser/sample.pdf, in linux environment. What should I change below?
import smtplib
fromaddr = 'myemail#gmail.com'
toaddrs = 'youremail#gmail.com'
msg = 'Hello'
# Credentials (if needed)
username = 'myemail'
password = 'yyyyyy'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
You create a message with an email package in this case -
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))
and then send the message.
import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
Several examples here - http://docs.python.org/library/email-examples.html
UPDATE
Updating the link since the above yields a 404 https://docs.python.org/2/library/email-examples.html. Thanks #Tshirtman
Update2: Simplest way to attach pdf
To attach the pdf use the pdf flag:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('me#gmail.com', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = 'me#gmail.com'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
The recommended way is using Python's email module in order to compose a properly
formatted MIME messages. See docs
For python 2
https://docs.python.org/2/library/email-examples.html
For python 3
https://docs.python.org/3/library/email.examples.html