I am trying to implement a functionality in python where I want to send a
file as an attachment to an email alert
Everything works fine. i am getting the email alert with required subject but the only problem is that I get the same attachment twice in my email alert.
fileMsg = email.mime.base.MIMEBase('application','octet-stream')
fileMsg.set_payload(file('/home/bsingh/python_files/file_dict.txt').read())
#email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=LogFile.txt')
emailMsg.attach(fileMsg)
# send email
server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(username, password)
server.sendmail(from_add, to_addr,emailMsg.as_string())
server.quit()
I have been having problems with this myself. I had 'alternative' as my message's MIMEMultipart type. When I changed to the default, 'mixed', the duplicate disappeared.
So if you created emailMsg using MIMEMultipart('alternative'), you may have the same problem.
I believe 'alternative' is for offering both a text and html version of the message body, so I think you need to offer both in addition to your attachment if you use it.
I hope that helps.
I have not found a good explanation of this anywhere yet; email can get pretty complicated.
The whole purpose of yagmail (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs.
Please try the following code:
import yagmail
yag = yagmail.SMTP(from_add, password)
contents = ['See my attachment below', '/home/bsingh/python_files/file_dict.txt']
yag.send(contents = contents)
Notice the magic here: contents is a list, where an item equal to a file path will automatically be loaded, mimetype guessed, and attached.
There's a lot more magic involved, such as easy to embed images, passwordless scripts, usernameless scripts, easy aliases, smart defaults (notice I omitted the to and subject arguments?) and much more. I advise/encourage you to read its github page :-). Feel free to raise issues or add feature requests!
You can get yagmail by using pip to install it:
pip install yagmail # Python 2
pip3 install yagmail # Python 3
There was an issue with the version..Has been resolved
Related
I'm currently trying to send mails with attachments.
However, I'm currently struggling to convert the file I'm supposed to receive.
Here's my request POST:
curl --form "file=#year.txt" http://localhost:8000/
I need to know how can I extract the file year.txt from my request, and then convert it to MIMEBase, so I can send it through EmailMessage.
file = request.POST.get('file')
email = EmailMessage(
subject,
content,
None,
['random#example.com'],
)
email.attach_file(file)
That'd be something like this; however, I'm not sure the process to follow. That's why I require your help.
EmailMessage does not support passing in the Subject etc. as arguments. Instead, you need something like
from email.message import EmailMessage
email = EmailMessage()
email["subject"] = subject
email["from"] = "you#example.org" # you need to pass in a sender too
email["to"] = "random#example.com"
email.set_content(content)
email.add_attachment(file, maintype="application", subtype="octet-stream")
If you have a more specific MIME type to use than the generic application/octet-stream, by all means use that instead. In this particular case, I guess text/plain would be correct and useful, but of course, that might not be applicable more generally, and really depends on your use case and application design.
See the examples from the email module documentation for variations and details.
Getting the generated message off your system is a separate topic which is often hard for beginners. If you run this in a place where you have an outgoing email server in the local network which doesn't require authentication, you should be able to simply create an smtplib.SMTP object and pass the message to its send_message method, but many real-world deployments have complications like requiring to authenticate to a remote server. There are, of course, many existing questions about that here, so please search before you ask a new question.
In Python I am trying to do 'send a password reset email', javascript reference (https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sendPasswordResetEmail). So far (and only recently) it looks like 'generate password reset link' was added (https://github.com/firebase/firebase-admin-python/releases). Does anyone know the next step in getting the email send? Do we send the email ourselves? If so, any suggestions? Is there a way to send the email in python directly?
Thanks for all your help in advance!
Might be late but for others to see:
email = 'user#example.com'
link = auth.generate_password_reset_link(email, action_code_settings)
# Construct password reset email from a template embedding the link, and send
# using a custom SMTP server.
send_custom_email(email, link)
More in here: https://firebase.google.com/docs/auth/admin/email-action-links#python_1
Thank you (bojeil-google) on Github for providing the answer. Apparently, the way to do this is to make a POST request per https://firebase.google.com/docs/reference/rest/auth/#section-send-password-reset-email . There is no direct call to do this in the python SDK. Thanks again!
Firebase-admin-sdk (python) is lack of methods to deal with user authentication. You can use Pyrebase. It's a wrapper for the firebase API.
I want to write a python that can sends data to a draft message, but NOT Send the mail directly.
Situation:
I'm a 3D animator. After done some shots, we need to send email(not internet, just in our company) to Lighting Team.
So we have some mail form, but sometimes we need to fix some words manual(version,texture..etc).
like below:
Shot Name : XXXX_seqXXX_scXXX
File Locate(hair + cloth) : please import X:\XX\XX\XX\XXX_ABC.ma
File include:
XXX_hair **(use version 1)**
XXX_cloth
ZZZ_cloth **(No texture)**
any problem please tell me.
Thanks.
Ezylryb
Question is:
Now I can write into a file, but I don't know how to open mail software(win7 Livemail) and create a new mail has these content. I'm try to use smtplib, but it will send mail directly..
Could anyone help me??
Many Thanks!!!!
Ezylryb
==============================
Finally, I write HTML code into a .html file, and a eml file with email address + Title + CC, and use os.startfile to open both files.
And I can copy/paste to draft email ^O^.
Coz we need some chinese words, so use big5 code in eml, and use qupori module to decode MIME words to Chinese words in html file.
A "draft" is a feature which your email client (in this case Win7 livemail) implements by itself. It's more or less just an email in a mailbox that the client hasn't sent yet. Mail folders like your "outbox" etc. are similar.
It's not something that Python has access to. If the mail client uses a standard mailbox format, you might be able to create the email and write it into the mailbox using mailbox module. If not, the best you can do is to write out your draft email into a file and then open that in your mail client and manually edit it.
I'm attempting to write a Python function to send an email to a list of users, using the default installed mail client. I want to open the email client, and give the user the opportunity to edit the list of users or the email body.
I did some searching, and according to here:
http://www.sightspecific.com/~mosh/WWW_FAQ/multrec.html
It's apparently against the RFC spec to put multiple comma-delimited recipients in a mailto link. However, that's the way everybody else seems to be doing it. What exactly is the modern stance on this?
Anyhow, I found the following two sites:
http://2ality.blogspot.com/2009/02/generate-emails-with-mailto-urls-and.html
http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx
which seem to suggest solutions using urllib.parse (url.parse.quote for me), and webbrowser.open.
I tried the sample code from the first link (2ality.blogspot.com), and that worked fine, and opened my default mail client. However, when I try to use the code in my own module, it seems to open up my default browser, for some weird reason. No funny text in the address bar, it just opens up the browser.
The email_incorrect_phone_numbers() function is in the Employees class, which contains a dictionary (employee_dict) of Employee objects, which themselves have a number of employee attributes (sn, givenName, mail etc.). Full code is actually here (Python - Converting CSV to Objects - Code Design)
from urllib.parse import quote
import webbrowser
....
def email_incorrect_phone_numbers(self):
email_list = []
for employee in self.employee_dict.values():
if not PhoneNumberFormats.standard_format.search(employee.telephoneNumber):
print(employee.telephoneNumber, employee.sn, employee.givenName, employee.mail)
email_list.append(employee.mail)
recipients = ', '.join(email_list)
webbrowser.open("mailto:%s?subject=%s&body=%s" %
(recipients, quote("testing"), quote('testing'))
)
Any suggestions?
Cheers,
Victor
Well, since you asked for suggestions: forget about the mailto: scheme and webbrowser, and write a small SMTP client using Python's smtplib module. It's standard, fully supported on all systems, and there's an example included in the documentation which you can practically just copy-and-paste pieces out of.
Of course, if you're using smtplib you will have to ask the user for the details of an SMTP server to use (hostname and port, and probably a login/password). That is admittedly inconvenient, so I can see why you'd want to delegate to existing programs on the system to handle the email. Problem is, there's no system-independent way to do that. Even the webbrowser module doesn't work everywhere; some people use systems on which the module isn't able to detect the default (or any) browser, and even when it can, what happens when you provide a mailto: link is entirely up to the browser.
If you don't want to or can't use SMTP, your best bet might be to write a custom module that is able to detect and open the default email client on as many different systems as possible - basically what the webbrowser module does, except for email clients instead of browsers. In that case it's up to you to identify what kinds of mail clients your users have installed and make sure you support them. If you're thorough enough, you could probably publish your module on PyPI (Python package index) and perhaps even get it included in a future version of the Python standard library - I'm sure there are plenty of people who would appreciate something like that.
As is often the case in Python, somebody's already done most of the hard work. Check out this recipe.
In the following line, there shouldn’t be a space after the comma.
recipients = ', '.join(email_list)
Furthermore, Outlook needs semicolons, not commas. Apart from that, mailto never gave me grief.
The general tip is to test mailto URLs manually in the browser first and to debug URLs by printing them out and entering them manually.
I use Gmail and an application that notifies me if I've received a new email, containing its title in a tooltip. (GmailNotifier with Miranda-IM) Most of the emails I receive are ones I don't want to read, and it's annoying having to login to Gmail on a slow connection just to delete said email. I believe plugin is closed source.
I've been (unsuccessfully) trying to write a script that will login and delete the 'top' email (the one most recently received). However this is not as easy I thought it would be.
I first tried using imaplib, but discovered that it doesn't contain any of the methods I hoped it would. It's a bit like the dbapi spec, containing only minimal functionality incase the imap spec is changed. I then tried reading the imap RFC (rfc3501). Halfway through it, I realized I didn't want to write an entire mail client, so decided to try using pop3 instead.
poplib is also minimal but seemingly has what I need. However pop3 doesn't appear to sort the messages in any order I'm familiar with. I have to either call top() or retr() on every single email to read the headers if I want to see the date received.
I could probably iterate through every single message header, searching for the most recent date, but that's ugly. I want to avoid parsing my entire mailbox if possible. I also don't want to 'pop' the mailbox and download any other messages.
It's been 6 hours now and I feel no closer to a solution than when I started. Am I overlooking something simple? Is there another library I could try? (I found a 'chilkat' one, but it's bloated to hell, and I was hoping to do this with the standard library)
import poplib
#connect to server
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!
#newest email has the highest message number
numMessages = len(mailserver.list()[1])
#confirm this is the right one, can comment these out later
newestEmail = mailserver.retr(numMessages)
print newestEmail
#most servers will not delete until you quit
mailserver.dele(numMessages)
mailserver.quit()
I worked with the poplib recently, writing a very primitive email client. I tested this with my email server (not gmail) on some test emails and it seemed to work correctly. I would send yourself a few dummy emails to test it out first.
Caveats:
Make sure you are using 'recent
mode':
http://mail.google.com/support/bin/answer.py?answer=47948
Make sure your Gmail account has POP3
enabled: Gmail > Settings >
Forwarding and POP/IMAP > "Enable POP
for all mail"
Hope this helps, it should be enough to get you going!