yahoo mail error 550, b'Request failed; Mailbox unavailable' - python

So this code works for gmail, when i tried it on yahoo mail i get this error, (550, b'Request failed; Mailbox unavailable')
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(emaill, pwd)
# select the label to work on
print('selecting inbox folder')
try:
mail.select('INBOX')
_, data = mail.search(None, '(UNSEEN)')
mail_ids = data[0]
id_list = mail_ids.split()
for mess in id_list:
_, data = mail.fetch(mess, '(RFC822)')
for response in data:
if isinstance(response, tuple):
print('preparing email body.........')
msg = email.message_from_string(response[1].decode('ISO-8859-1'), policy=email.policy.default)
# open_links(msg)
body_of_email = 'Hi'
email_from = msg['from']
email_to = msg['to']
subject = msg['subject']
mssg = MIMEText(body_of_email, 'plain')
mssg['Subject'] = subject
mssg['From'] = email_from
mssg['To'] = email_to
mssg['Message-ID'] = msg['Message-ID']
try:
# msg.add_header('reply-to', email_to)
s = smtplib.SMTP_SSL(host=smtp_server, port=port)
# .starttls()
s.login(user=emaill, password=pwd)
s.sendmail(emaill, msg['From'], mssg.as_string())
the above code won't work but I change the message to let say 'hey you, it works, so am thinking there is a problem with the MIMETest construction, any help please

Related

I can't send a message from telegram to mail

When entering a message , the console outputs that the "ms" variable is empty , how can this be fixed ?
def send_mail(id_user, message_topic):
data = read_date_json()
ms = ''
login = data['MyDate'][0]['login']
password = data['MyDate'][0]['password']
mail = data['MyDate'][0]['login'].split('#')[1]
if ('yandex' in mail) or ('ya' in mail):
ms = 'yandex.ru'
elif 'gmail' in mail:
ms = 'gmail.com'
elif 'mail' in mail:
ms = 'mail.ru'
url = data['Mail'][0][ms]
number, topic, message = message_topic.split('$')
toaddr = data['MyFriend'][0]['mail'][int(number)]
msg = MIMEMultipart()
msg['Subject'] = topic
msg['From'] = login
body = message
msg.attach(MIMEText(body, 'plain'))
try:
server = root.SMTP_SSL(url, 465)
except:
print('no connect')
server.login(login, password)
server.sendmail(login, toaddr, msg.as_string())
server.quit()
bot.send_message(id_user, 'Ваше сообщение отправлено')
I tried to overwrite variables and tried to use other mail, but to no avail

Forward email with attachment

I want to resend email with attachments in Python. I have this code for sending email but how can I reference to attachment in another email?
Sending
def show_emails():
M.select()
typ, data = M.search(None, 'All')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
parser = Parser()
email = parser.parsestr(data[0][1])
print "MESSAGE NUMBER %s" % (num)
print 'Raw Date:'
print email.get('Date')
print "From:"
print email.get('From')
print "Subject: "
print email.get('Subject')
And this code is for sending
msg = MIMEMultipart()
mfrom = 'from#abc.com'
mto = 'to#abc.com'
msg['Subject'] = 'test'
msg['From'] = mfrom
msg['To'] = mto
msg['Date'] = formatdate()
# Open the file to scan in binary mode
fp = open('/path/to/file', 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="filename"')
fp.close()
msg.attach(attachment)
I know I need to check if there is any attachment. And how can I reference to attachment and forward it?
if msg.is_multipart():
for part in msg.walk():
fileName = part.get_filename()
if bool(fileName):
print "Attachment: %s " % (decode_header(fileName)[0][0])
else:
print "No attachments"
You cannot just reference it: that's what RFCs 4467-9 were for, but those weren't implemented by many servers and at this point I think they're dead. You have to download the attachment and send it as if you were sending a local file.

python smtplib multipart email body not showing on iphone

I am trying to send an email with an image using smtplib in python. The email shows up fine on my desktop and on the iphone gmail app, but on the standard iphone mail app the body doesn't appear. Here is my code:
def send_html_email(self, subject, html, to_email,from_email, password, from_name, image=None):
msg = MIMEMultipart('alternative')
msg['From'] = from_name
msg['To'] = to_email
msg['Subject'] = subject
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msg.as_string().encode('utf-8'))
session.quit()
It seems that when I do not add an image, the email sends fine with the body. Any ideas on how to get it working with the image as well?
This appears to work:
def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
msgRoot = MIMEMultipart('related')
msgRoot['From'] = from_name
msgRoot['To'] = to_email
msgRoot['Subject'] = subject
msg = MIMEMultipart('alternative')
msgRoot.attach(msg)
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
session.quit()

How to get unread messages and set message read flags over IMAP using Python?

import imaplib
def read():
userName = "xxx#gmail.com"
password = "xxxx"
name = 'xxx#gmail.com'
email_ids = [userName]
data = []
imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
imap_server.login(userName, password)
imap_server.select('INBOX')
da = []
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount
status, response = imap_server.search(None, '(FROM "xxx#gmail.com")')
email_ids = [e_id for e_id in response[0].split()]
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
da.append(response[0][1])
print da
read()
How to organise the code above, to read only unread mails?
Also, once we read them, how to mark the messages as read mail using Python?
import imaplib
def read(username, password, sender_of_interest):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(username, password)
imap.select('INBOX')
# Use search(), not status()
status, response = imap.search(None, 'INBOX', '(UNSEEN)')
unread_msg_nums = response[0].split()
# Print the count of all unread messages
print len(unread_msg_nums)
# Print all unread messages from a certain sender of interest
status, response = imap.search(None, '(UNSEEN)', '(FROM "%s")' % (sender_of_interest))
unread_msg_nums = response[0].split()
da = []
for e_id in unread_msg_nums:
_, response = imap.fetch(e_id, '(UID BODY[TEXT])')
da.append(response[0][1])
print da
# Mark them as seen
for e_id in unread_msg_nums:
imap.store(e_id, '+FLAGS', '\Seen')
def read(username, password, sender_of_interest=None):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(username, password)
imap.select('INBOX')
# Use search(), not status()
# Print all unread messages from a certain sender of interest
if sender_of_interest:
status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
else:
status, response = imap.uid('search', None, 'UNSEEN')
if status == 'OK':
unread_msg_nums = response[0].split()
else:
unread_msg_nums = []
data_list = []
for e_id in unread_msg_nums:
data_dict = {}
e_id = e_id.decode('utf-8')
_, response = imap.uid('fetch', e_id, '(RFC822)')
html = response[0][1].decode('utf-8')
email_message = email.message_from_string(html)
data_dict['mail_to'] = email_message['To']
data_dict['mail_subject'] = email_message['Subject']
data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
data_dict['body'] = email_message.get_payload()
data_list.append(data_dict)
print(data_list)
You may use my lib - imap_tools:
https://pypi.org/project/imap-tools/
from imap_tools import MailBox, A
# get subjects of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test#mail.com', 'pwd') as mailbox:
subjects = [msg.subject for msg in mailbox.fetch(A(seen=False), mark_seen=True)]

Email multiple recipients Python

I'm trying to email multiple recipients using the pyton script below. I've searched the forum for answers, but have not been able to implement any of them correctly. If anyone has a moment to review my script and spot/resolve the problem it would be greatly appreciated.
Here's my script, I gather my issue is in the 'sendmail' portion, but can't figure out how to fix it:
gmail_user = "sender#email.com"
gmail_pwd = "sender_password"
recipients = ['recipient1#email.com','recipient2#email.com']
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
mail("recipient1#email.com, recipient2#email.com",
"Subject",
"Message",
"attchachment")
Any insight would be greatly appreciated.
Best,
Matt
It should be more like
mail(["recipient1#email.com", "recipient2#email.com"],
"Subject",
"Message",
"attchachment")
You already have a array of recipients declared,that too globally,You can use that without passing it as an argument to mail.
I wrote this bit of code to do exactly what you want. If you find a bug let me know (I've tested it and it works):
import email as em
import smtplib as smtp
import os
ENDPOINTS = {KEY: 'value#domain.com'}
class BoxWriter(object):
def __init__(self):
pass
def dispatch(self, files, box_target, additional_targets=None, email_subject=None, body='New figures'):
"""
Send an email to multiple recipients
:param files: list of files to send--requires full path
:param box_target: Relevant entry ENDPOINTS dict
:param additional_targets: other addresses to send the same email
:param email_subject: optional title for email
"""
destination = ENDPOINTS.get(box_target, None)
if destination is None:
raise Exception('Target folder on Box does not exist')
recipients = [destination]
if additional_targets is not None:
recipients.extend(additional_targets)
subject = 'Updating files'
if email_subject is not None:
subject = email_subject
message = em.MIMEMultipart.MIMEMultipart()
message['From'] = 'user#domain.com'
message['To'] = ', '.join(recipients)
message['Date'] = em.Utils.formatdate(localtime=True)
message['Subject'] = subject
message.attach(em.MIMEText.MIMEText(body + '\n' +'Contents: \n{0}'.format('\n'.join(files))))
for f in files:
base = em.MIMEBase.MIMEBase('application', "octet-stream")
base.set_payload(open(f, 'rb').read())
em.Encoders.encode_base64(base)
base.add_header('Content-Disposition', 'attachment; filename={0}'.format(os.path.basename(f)))
message.attach(base)
conn = smtp.SMTP('smtp.gmail.com', 587)
un = 'user#gmail.com'
pw = 'test1234'
conn.starttls()
conn.login(un, pw)
conn.sendmail('user#domain.com', recipients, message.as_string())
conn.close()
I was facing the same issue, I fixed this issue now. Here is my code -
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import datetime
def sendMail():
message = MIMEMultipart()
message["To"] = "xxxxx#xxxx.com,yyyy#yyyy.com"
message["Cc"] = "zzzzzz#gmail.com,*********#gmail.com"
message["From"] = "xxxxxxxx#gmail.com"
message["Password"] = "***************"
server = 'smtp.gmail.com:587'
try:
now = datetime.datetime.now()
message['Subject'] = "cxxdRL Table status (Super Important Message) - "+str(now)
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(message["From"], message["Password"])
server.sendmail(message["From"], message["To"].split(",") + message["Cc"].split(","), message.as_string())
server.quit()
print('Mail sent')
except:
print('Something went wrong...')
sendMail()

Categories

Resources