I am using smtplib to send a copy of my friends history to myself, however it sends nothing to me just a plain email, anyone know what the problem is?
with open ("History.txt", ) as myfile:
data=myfile.readlines()
data = str(data)
data = "'" + data + "'"
import smtplib
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login('myemail','mypassword')
server.sendmail('myemail', 'myotheremail', data)
Use EmailMessage instead.
Python » Documentation email: Examples.
a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.
Related
I've just joined a project and have been trying to figure why some emails are showing up as they should on Gmail but when I open then with a client like Thunderbird or Outlook the attached PDFs do now show up.
As an additional detail if I forward the mail from Thunderbird/Tutlook to a Gmail account the attached pdf will appear and if I send it back to the Thunderbird/Outlook - connected account it will again appear, so Gmail fixes something that's wrong in the code.
This is my second time dealing with emails, the first being mostly copying some code to see if it works, so if you're willing to explain it to me in addition to helping me fix it, I'd appreciate it greatly.
I'll post the code here and then add some additional information on what I tried below, to keep this a bit cleaner.
So, here's the code:
from email.message import EmailMessage
from email import encoders
from email.mime.base import MIMEBase
import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = "someaddress"
msg['To'] = user_email
msg.set_content('Certification')
msg.add_alternative("""<!DOCTYPE html>
<html>
<body>
Stuff...
</body>
</html>
""", subtype='html')
filename = 'somefilename'
pdf_filename = 'certificate.pdf'
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
"attachment", filename=pdf_filename
)
try:
msg.attach(part)
with smtplib.SMTP('someIP', port) as smtp:
smtp.send_message(msg)
I've seen some similar issues (or actually the same issue) before, and some solutions suggested using a MIMEMultipart-mixed message object instead of an email one like this:
msg=MIMEMultipart('mixed') instead of msg = EmailMessage() but because add_alternative is not a MIMEMultipart method, I cannot do that without changing that part.
(The above was suggested on this post - which is exactly the same issue as mine, but unfortunately I could not use the same fix)
What I tried doing was calling a
msg.make_mixed() below msg=Email.Message() hoping that the mixed type (I don't understand email types yet) would solve the problem, but when I tried sending an email that way I got a Status=4, Failed to send file, error.
I would also really appreciate if you could offer any suggestion for a resource to learn some more about sending and receiving emails (from a python perspective).
Thank you!
The problem here is that you have directly attached a pre-built MIME part to a multipart/alternative message. It ends in an incorrect message that may be poorly processed by mail readers.
In the email.message interface, you should use the add_attachement method. It will handle the base64 encoding and will change the message into a multipart/mixed one:
with open(filename, "rb") as attachment:
msg.add_attachment(attachment.read(), maintype='application',
subtype='octet-stream', filename=pdf_filename)
try:
with smtplib.SMTP('someIP', port) as smtp:
smtp.send_message(msg)
I'm trying to send a simple mail with SendGrid which must contain one hyperlink.
I'm not doing anything fancy, just following the documentation example with some changes
import os
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test#example.com")
to_email = To("test#example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/html", '<html>google</html>')
mail = Mail(from_email, to_email, subject, content)
response = sg.client.mail.send.post(request_body=mail.get())
It looks fine to me, but once I run the script and the mail is sent, it shows up like plain text I cannot click on.
I also tried many other combinations removing the <html> tag, using single and double quotes with the backslash, but nothing really worked. I even tried to do the same thing without the Mail Helper Class, but it didn't work.
Thanks very much for the help.
content = Content(
"text/html", "Hi User, \n This is a test email.\n This is to also check if hyperlinks work <a href='https://www.google./com'> Google </a> Regards Karthik")
This helped me. I believe you don't need to mention the html tags
I want to send an email to multiple users. Right now, I am only able to send it to one user. I want to make a property file so that whenever I need to add or remove any user from the list, I dont have to edit anything in .py file.
I am able to send the email to one user
import smtplib
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = abc#an.com
you = jud#gm.com
msg = MIMEMultipart('alternative')
msg['Subject']="subject of the email"
msg['From"]=me
msg['To']=you
text="hi"
html= '''body of email'''
part1=MIMEText(text, 'plain')
part1=MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP(host,port)
s.sendmail(me,you, msg.as_string())
s.quit()
the email should go to multiple users.
The argument you can be a list of email addresses. You will need to adapt your code to set the To: header to accept a list of strings
msg['To'] = '.'.join(you)
or you can use a placeholder like
msg['To'] = 'undisclosed-recipients:;'
but other than that, your existing code should just work.
In some more detail, the latter is basically equivalent to putting all the addresses in a Bcc: header, so that the recipients cannot see each others' addresses.
To populate you from a file, try
with open(filename) as f:
you = f.readlines()
where the file contains one email address per line.
I'm making an API using Python requests, and HTTP GET is working fine, but I'm having a little bit of trouble with HTTP POST. So, as with a lot of websites, you can read information, but in order to make a post request (such as following a user, or writing a post), you need to have an authenticated session. THIS website, uses google to log in. Normally, I would just pass the username:password into the POST request formdata to log in, but this google thing is pretty wonky (and quite frankly I'm not that experienced). Does anyone have a reference or an example to help me out? ;/
I do not know about python requests but to send an email its as easy as this
import yagmail
yagmail.SMTP(emailh).send(email, subject, body)
#emailh = your email (just username no #gmail.com)
#email = send to (full email including domain ***#gmail.com or ***#outlook.com)
#subject = subject of the message
#body = body of the message
Even better
emailh = raw_input('Your email: ')
email = raw_input('Send to: ')
subject = raw_input('Subject: ')
body = raw_input('Body: ')
yagmail.SMTP(emailh).send(email, subject, body)
print('Email Sent.')
If this is what you are talking about anyway.
This page might be useful link
I'm having a file.txt file which has many lines. I want that any one line is chosen at random and emailed. This is looped thrice.
import smtplib,datetime,random
def mail(em):
#print "yo"
fromAddress = "atadmorecouth#gmail.com"
toAddress = "atadmorecouth#gmail.com"
subject = "WOW " + str(datetime.datetime.now())
#print subject
msg = em
server=smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
password = "mypassword"
server.login(fromAddress, password)
server.sendmail(fromAddress, toAddress, msg)
#print server.sendmail(fromAddress, toAddress, msg)
for i in range(0,3):
em=str(random.choice(list(open('file.txt'))))
mail(em)
This code does not work. The login and everything is fine. The only problem I notice is that server.sendmail(fromAddress, toAddress, msg) returns an empty {}
What could be the possible fix to this? Whats the problem in first place?
I have run the mail() function in the terminal and that seems to work fine.
All the files are hosted here
First, as the docs say:
If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused.
So, the fact that you're getting back {} isn't a problem; it means that you had no errors.
Second, what you're sending is not a valid message. A message must contain headers, then a blank line, then the body. And the headers should contain at least From: and To:.
The smtplib library doesn't do this for you; as explained in the example:
Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.
...
Note: In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.
Or, in the sendmail docs:
Note: The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. The SMTP does not modify the message headers in any way.
In this case (as in the example), it's simple enough to just craft the message manually:
msg = "From: {}\r\nTo: {}\r\n\r\n{}\r\n".format(fromAddress, toAddress, em)
Finally, you really should call server.quit() at the end of the mail function. While (at least in CPython) the server object will be destroyed as soon as the function ends, unlike many other objects in Python, SMTP objects do not call close when destroyed, much less quit. So, from the server's point of view, you're suddenly dropping connection. While the RFCs suggest that a server should work just fine without a QUIT, and most of them do, they also recommend that the client should always send it and wait for a response, so… why not do it?