I have an automated messaging system that sends emails with the three standard parameters, those being: To, destination and subject. The message is immediately sent after an error has been detected.
The message is being sent over Python, it receives the HTML-body from the monitoring system, it's NOT in the script itself. However, after I used mail-tester it came to light that I was missing the 'to' and 'date' header. However, I can't seem to find a way to add either of these two. I did some research and found out that there you can add mail options but can't find any parameters for this.
I also intend to send a plain-text only copy.
If there isn't an answer to this problem, what code should I try next to try and nail it down, PHP?
#!/usr/bin/env python
list1=[0, 1, 2, 3, 4];
import mimetypes, os, smtplib, sys
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
FROM='x#xx.com'
SRVSMTP='mysmtpserver:587'
DESTINATION=sys.argv[1]
SUBJECT=sys.argv[2]
MESSAGE=sys.argv[3]
PASS='xxxxxx'
msg = MIMEMultipart()
msg['From'] = FROM
msg['Subject'] = SUBJECT
msg['To'] = DESTINATION
msg['Date'] = formatdate()
msg.attach(MIMEText(MESSAGE, 'html', 'utf-8'))
raw = msg.as_string()
smtpserver = smtplib.SMTP(SRVSMTP)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(FROM, PASS)
smtpserver.sendmail(FROM, DESTINATION , raw)
Related
So I'm trying to send an e-mail from Excel with Python. Right now I just have all the e-mails set up in column A1 separated by semicolons. If I put the e-mails into Python directly, they send out but when I use the Python call-out, it freaks out giving me this error. How exactly can I make this work?
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas
from datetime import datetime
server = smtplib.SMTP('relay.xxx.com')
email_df = pandas.read_excel(f"E-mails.xlsx", sheet_name="Emails", nrows=1, usecols = "A")
sender = 'email#email.com'
receivers = 'Email'
receivers = list(email_df)
print(receivers)
msg = MIMEMultipart('related')
msg['Subject'] = 'Test mail'
msg['From'] = sender
with smtplib.SMTP('relay.xxx.com') as server:
msg['To'] = receivers
server.sendmail(sender, receivers, bytes(msg.as_string()))
print(f"Successfully sent email to: {receivers}")
I don't want multiple e-mails to be sent out. I want 1 single e-mail with a bunch of e-mails in the address box.
Alternatively, if there's a way can read it by column, (addr1 in a1, addr in a2) that'd also be better.
Appreciate it.
If you can get your email addresses (from your df) into a list in the desired format, e.g.:
print(receivers)
['email1#email1.com', 'email2#email2.com', 'email3#email3.com']
then you can add this after its assignment to turn it into a string for send_mail (as it requires a string instead of a list):
receivers = ", ".join(receivers)
You mention that it would be ideal if you had an email address per row under column A in your spreadsheet. So if you can get your Excel spreadsheet into this format (with a column heading of "Email") then you can do this to get the aforementioned list:
email_df = pandas.read_excel(f"E-mails.xlsx", sheet_name="Emails", usecols = "A")
receivers = email_df['Email'].tolist()
So, for completeness (with Excel spreadsheet in its new format of one email address per row under column A), your code would change to:
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas
from datetime import datetime
server = smtplib.SMTP('relay.xxx.com')
email_df = pandas.read_excel(f"E-mails.xlsx", sheet_name="Emails")
receivers = email_df['Email'].tolist()
print(receivers) # Check list is one valid email address per element
receivers = ", ".join(receivers)
sender = 'email#email.com'
msg = MIMEMultipart('related')
msg['Subject'] = 'Test mail'
msg['From'] = sender
with smtplib.SMTP('relay.xxx.com') as server:
msg['To'] = receivers
server.sendmail(sender, receivers, bytes(msg.as_string(), encoding='utf-8'))
print(f"Successfully sent email to: {receivers}")
If you build a message, you'd better use the send_message interface. And I would suggest to use the newer EmailMessage interface which is cleaner and simpler that the older MimeMultipart one:
import smtplib
from email.message import EmailMessage
...
msg = EmailMessage()
msg['Subject'] = 'Test mail'
msg['From'] = sender
msg.set_payload('Message text.\nLine 2...')
# or eventually add parts with msg.add_related(...), msg.add_alternative(..)
# or msg.add_attachment(...)
with smtplib.SMTP('relay.xxx.com') as server:
msg['To'] = receivers
server.send_messages(msg)
print(f"Successfully sent email to: {receivers}")
I am using Python to send a simple HTML email and have the basic code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
def send_test_mail(body):
sender_email = <SenderEmail>
receiver_email = <ReceiverEmail>
msg = MIMEMultipart()
msg['Subject'] = '[Email Test]'
msg['From'] = sender_email
msg['To'] = receiver_email
msgText = MIMEText('<b>%s</b>' % (body), 'html')
msg.attach(msgText)
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 587) as smtpObj:
smtpObj.ehlo()
smtpObj.login(<LoginUserName>, <LoginPassword>)
smtpObj.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
print(e)
if __name__ == "__main__":
send_test_mail("Welcome to Medium!")
This has been put together from a couple of sources from within the stackexchange community but the intention is only to send a straightforward email.
But, when it is received, I get the paperclip icon indicating there is an attachment when there clearly isn't one.
https://i.stack.imgur.com/Ysj3g.png
Python is not my strong point but I'm sure it has more to do with SMTPLIB rather than python.
Does anyone know what is going on here?
Thanks
This is the code I have at the moment. Does anyone know how to work off of it in order to reply to a message instead, of just sending a new one to the same user? I've looked at many different Stack Overflow pages, and I've tried to implement the same things in my code. However, it just sends the message to the user, and I could not understand the explanations on the other pages.
import smtplib
import vacci_bot
from modules import *
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import email
load_dotenv(find_dotenv())
USER = os.environ.get("ADRESS")
PASS = os.environ.get("PASSWORD")
def send_mail(email, postal_code):
with smtplib.SMTP("smtp.gmail.com", 587) as smpt:
initialize(smpt)
smpt.login(USER, PASS)
msg = vacci_bot.scrape(postal_code)
send_message, to_adress = message(email, msg, postal_code)
print(send_message, to_adress, postal_code)
smpt.sendmail(USER, to_adress, send_message)
def initialize(smpt):
smpt.ehlo()
smpt.starttls()
smpt.ehlo()
def message(email, text, postal_code):
body = MIMEText(text)
message = MIMEMultipart()
message["to"] = email
message['from'] = USER
message['subject'] = f'Vaccines near {postal_code}'
message.add_header('reply-to', email)
message.attach(body)
return message.as_string(), [message["to"]]
I am trying to send email automatically from my official ID to another official ID. For that I have used following python script.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "<SENDER MAIL ID>"
toaddr = "<RECIPIENT MAIL ID>"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "Robot Uprising, We are coming for you"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
While executing this I am facing issue as follows:
Traceback (most recent call last):
File "mailsendtest.py", line 2, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named MIMEMultipart
I am a starter in python. Kindly provide inputs. Thanks !
I find two problems with your imports assuming you're using Python3.
Change from email.MIMEMultipart import MIMEMultipart to from email.mime.multipart import MIMEMultipart
Change from email.MIMEText import MIMEText to from email.mime.text import MIMEText
Also make sure you have the libraries installed if these don't work.
I followed a tutorial in youtube for sending email in python using outlook, however I have received an error when running the python file.
This is my python script :
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
sender_email_address = 'nmahirahaqilah.awahab#gmail.com'
sender_email_password = 'mypassword'
receiver_email_address = 'mahirah.abd.wahab#ericsson.com'
email_subject_line = 'Sample python email'
msg = MIMEMultipart()
msg['From'] = sender_email_address
msg['To'] = receiver_email_address
msg['Subject'] = email_subject_line
email_body = 'Hello World'
msg.attach(MIMEText(email_body,'plain'))
email_content = msg.as_string()
server = smtplib.SMTP('smtp.mail.outlook.com:587')
serverstarttls()
server.login(sender_email_address,sender_email_password)
server.sendmail(sender_email_address,receiver_email_address,email_content)
server.quit()
This is the error that I am receiving, not quite sure why:
C:\Users\Azril\Desktop>python email.py
File "email.py", line 3
from email.mime.text
^
SyntaxError: invalid syntax
Appreciate your help on this.