How to reply to a message using SMTP and IMAP? - python

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"]]

Related

How i can login in Gmail with Python?

The idea of ​​my code is to send a message to the mail ( x ) from the mail that I go to using the Login in the code. 17 line causes an error.
#main.py
import config as cfg
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
to_email = 'dasdladalffhalf'
msg['Subject'] = input('Topic: ')
msg['From'] = cfg.LOGIN
msg_body = input('Text: ')
msg.attach(MIMEText(msg_body, 'plain'))
server = smtplib.SMTP_SSL('smtp.gmail.com: 587')
server.login(cfg.LOGIN, cfg.PASSWORD)
server.sendmail(cfg.LOGIN, to_email, msg.as_string())
#config.py
LOGIN = 'login'
PASSWORD = "password"
You will have to enable less secure apps in GMail for this to work. https://myaccount.google.com/lesssecureapps
Sometimes you may also have to complete a captcha while logged into GMail - https://accounts.google.com/DisplayUnlockCaptcha
More info: https://support.google.com/accounts/answer/6010255?hl=en

How to solve smtplib.SMTPDataError: (554, b'5.5.1 Error: no valid recipients') in python

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.

Email with no attachment is showing paperclip

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

How do I use MIMEMultipart?

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

Python mail headers

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)

Categories

Resources