I want to make a script that sends my homework to my mail every now and then, but they sending a mail part isn't working. I have looked at tutorials, but I still get a mistake when i write
msg = MIMEMultipart()
Is there something wrong with that?
(I use gmail)
for name, email in zip(names, emails):
print("Writing the mail")
msg = MIMEMultipart()
# add in the actual person name to the message template
message = message_template.substitute(PERSON_NAME=name.title())
# setup the parameters of the message
msg['From']=Myaddress
msg['To']=email
msg['Subject']="Homework"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# send the message via the server set up earlier.
s.send_message(msg)
print("Mail sent")
del msg
btw I have multiple mails to send it to.
And yes I imported these:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Related
I created a script in python to email with an attachment. I put it in databricks, and put it on a schedule. When I manually run this function, it fires only one email, but when it runs on the schedule, to emails are sent to each recipient. Although it sounds like a schedule issue, I believe it's a code issue - I was able to get it to work at some point, but now it is sending again.
If anyone can take a look at the code below and see if they can figure out why it would be duplicating, it would be appreciated!
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from datetime import date
def SendEmail(recipient, subject,message_records,attach,cc,bcc,df):
server = smtplib.SMTP ('smtp.sendgrid.net', 587) # check server and port with your provider
server.ehlo()
server.starttls()
server.login("apikey", dbutils.secrets.get(scope = "XXXX", key = "XXXX")) # insert secret name
sender = dbutils.secrets.get(scope = "XXXX", key = "XXXX") # insert secret name
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = "noreply#noreply.com"
msg['cc'] = ", ".join([cc])
msg['To'] = recipient
rcpt = bcc.split(",") +cc.split(",") + [recipient]
message = """
<html>
<body>
Good morning, <br> <br>
"""+message_records+"""<br> <br>
Thank you and have a wonderful day!
</body>
</html>
"""
if attach==1:
msg.attach(MIMEText(message,'html'))
filename = "ASN-" + str(date.today())+'.csv'
attachment = MIMEApplication(df.to_csv(index=False))
attachment["Content-Disposition"] = 'attachment; filename=" {}"'.format(filename)
msg.attach(attachment)
else:
msg.attach(MIMEText(message,'html'))
server.sendmail(sender, rcpt, msg.as_string())
server.close()```
I suggest you look at the SENDGRID library for python. It uses the API key that you get from the service and it is built just for this service.
https://docs.sendgrid.com/for-developers/sending-email/v3-python-code-example
See if this code produces the same duplicate issue you are seeing.
If I remember right, send grid keeps track of the sent mail messages. Make sure the "to - recipient" list does not have duplicate addresses.
I do not see any obvious issues with the above code.
Here is the PyPi link. There are a ton of examples on usage.
https://pypi.org/project/sendgrid/
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 want to send a status mail once a day using a cron job using smtplib.
Sending of the mail works well, however the sending time and date always seems to be the time and date when I read the mail, but not when the mail is sent. This may be 6 hours later.
I have not found hints on providing a sending time to smtplib, together with the message data. Am I missing anything or is this a problem with my mail server configuration? However, other mails handed in via Thunderbird do not show this effect with this account.
My python program (with login data removed) is listed below:
import smtplib
sender = 'abc#def.com'
receivers = ['z#def.com']
message = """From: Sender <abc#def.com>
To: Receiver<z#def.com>
Subject: Testmail
Hello World.
"""
try:
smtpObj = smtplib.SMTP('mailprovider.mailprovider.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
[EDIT]
Code using email package as suggested, but still the time shown in my inbox is reading time and not sending time.
import smtplib
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Adding an explicit Date field to the message did the trick, thank you to Serge Ballesta for the idea:
import smtplib
from email.utils import formatdate
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
msg["Date"] = formatdate(localtime=True)
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
You might have to specify more information in the headers of your message. Try using the email module to build your message instead of assembling the text yourself.
Perhaps it's stupid, but do you have correct date and time on the server?
After replacing headers like from,to,sub i am able to forward mail to another email address.
But how can I forward mail by adding more attachments and more text or html content.
As we see in the gmail, new contents should be displayed before the forwrded message content. Any idea on how could we achieve this?
Forwarded mail can be multipart or not.
But since we add new content it will be multipart
I have tried the code below
# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host,993)
client.login(user, passwd)
client.select('INBOX')
result, data = client.uid('fetch', msg_id, "(RFC822)")
client.close()
client.logout()
# create a Message instance from the email data
message = email.message_from_string(data[0][1])
# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
message.replace_header("Subject", "Fwd:"+ message["Subject"].replace("FWD: ", "").replace("Fwd: ","" ))
# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP_SSL(smtp_host, smtp_port)
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()
I was able to achieve this using the email package, attaching the original email as a part:
from email.message import Message
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage
from email import message_from_bytes
raw_email = get_raw_email() # get the original email from wherever
original_email = message_from_bytes(raw_email)
part1 = MIMEText("This is new content")
part2 = MIMEMessage(original_email)
new_email = MIMEMultipart()
new_email['Subject'] = "My subject"
new_email['From'] = 'abc#xyz.com'
new_email['To'] = '123#456.com'
new_email.attach(part1)
new_email.attach(part2)
I am trying to send auto generated mail with attachment for a list of recipiant.I have written one class Mail like this:-
Its sending mail with proper data but sometime some recipiant are not getting mail in proper time and some are getting mail when i run this file.Those guys who are not getting the mail in proper time are getting the same mail after a lot of time.(it depends 1hr-10hr).
Don't know whats the problem ?
Is there any restriction for perticular domain or perticular id? like i can send only 5 or 10 auto generated mail within 1hr or 2 hr?
class Mail:
def send_mail(self,recipient,message,filepath):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
Userid = 'mail#domain.in'
Password = 'password'
for rec in recipient:
msg = MIMEMultipart()
msg['From'] = 'no-reply#test.in'
msg['To'] = rec
msg['Subject'] = "Daily Mail"
msg.attach(MIMEText(message))
f = file(filepath)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='download file')
msg.attach(attachment)
mailServer = smtplib.SMTP('smtpauth.mydomain.in', 587)
mailServer.ehlo()
#mailServer.starttls()
mailServer.ehlo()
mailServer.login(Userid, Password)
mailServer.sendmail(Userid, rec, msg.as_string())
mailServer.close()
here i am trying to send the mail:-
m = Mail()
m.send_mail(['mail1#gmail.com','mail2#somedomain.in','mail3#otherdomain.in','mail4#gmail.com'],'helloooooooo','C:/Office/file/myfile.xlsx')
Yes there might be limitations both on your "smtpauth.mydomain.in" mail server and on the receiving mail servers.
Multiple identical mails from one sender to a lot of different destinations might get stuck in different spam filters.
To get the exact limitations of how often you can send mails I guess you have to ask your mail service provider.