I have a test.html file that I want to send via email(I am refering about the page content). Is there a way for getting the information from the html and sending it as a email? If you have any other ideas please share.
Here's a quick and dirty script I just wrote which might be what you're looking for.
https://gist.github.com/1790847
"""
this is a quick and dirty script to send HTML email - emphasis on dirty :)
python emailpage.py http://www.sente.cc
made to answer: http://stackoverflow.com/questions/9226719/sending-a-html-file-via-python
Stuart Powers
"""
import lxml.html
import smtplib
import sys
import os
page = sys.argv[1] #the webpage to send
root = lxml.html.parse(page).getroot()
root.make_links_absolute()
content = lxml.html.tostring(root)
message = """From: Stuart Powers <stuart.powers#gmail.com>
To: Stuart Powers <stuart.powers#gmail.com>
MIME-Version: 1.0
Content-type: text/html
Subject: %s
%s""" %(page, content)
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.starttls()
smtpserver.login("stuart.powers#gmail.com",os.environ["GPASS"])
smtpserver.sendmail('stuart.powers#gmail.com', ['stuart.powers#gmail.com'], message)
There are many ways of reading files in python and there are also ways to send emails in python. Why don't you look up the documentation and come back with some coding error ?
Sending emails in python: http://docs.python.org/library/email-examples.html
Reading files in python: http://docs.python.org/tutorial/inputoutput.html
Related
TPA.wsdl https://pastebin.com/7DBhCHbv
DataService.xsd https://pastebin.com/AFhg64hH
from zeep import Client
import base64
from requests import Session
from zeep.wsse.username import UsernameToken
from zeep.transports import Transport
from zeep.exceptions import Fault
Username = '....'
Password = '....'
sendFile = 'V07_220110.ffdata'
session = Session()
session.verify = False
try:
wsdl = 'TPA.wsdl'
# initialize zeep client
client = Client(
wsdl=wsdl,
wsse=UsernameToken(Username, Password),
transport=Transport(session=session)
)
with open(sendFile, "rb") as pdf_file:
encoded_string = base64.b64encode(pdf_file.read())
with client.options(raw_response=True):
node = client.service.uploadEdasDraft(sendFile, encoded_string )
print(node.content)
except Fault as fault:
parsed_fault_detail = client.wsdl.types.deserialize(fault.detail[0])
Always getting Response
I got error ORA-31011: XML parsing failed
From SOAPUI everything sending ok with Enable MTOM settings
So how to make request to it, and how debug sending requests?
Based on that WSDL file, a code like this:
from zeep import Client
from zeep.wsse.username import UsernameToken
username = 'username'
password = 'p#$$word'
file_name = 'test.txt'
client = Client(wsdl = 'TPA.wsdl',
wsse = UsernameToken(username, password))
with open(file_name, "rb") as f:
content = f.read()
client.service.uploadEdasDraft(file_name, content)
should produce something like this:
<soap-env:Envelope xmlns:soap-env="http://www.w3.org/2003/05/soap-envelope">
<soap-env:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>username</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">p#$$word</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soap-env:Header>
<soap-env:Body>
<ns0:uploadEdasDraft xmlns:ns0="http://types.data.external.ws.edas.sodra.epr.lt">
<fileName>test.txt</fileName>
<document>dGhpcyBpcyBhIHRlc3QNCnRoaXMgaXMgYSB0ZXN0DQp0aGlzIGlzIGEgdGVzdA0KdGhpcyBpcyBhIHRlc3QNCg==</document>
</ns0:uploadEdasDraft>
</soap-env:Body>
</soap-env:Envelope>
Since the document type is marked as xsd:base64Binary zeep should handle the base64 encoding for you (your code seems to be doing the encoding twice).
In the example above I'm using a text file, but I assume your file named V07_220110.ffdata is an XML file, since that's what this attribute says: xmime:expectedContentTypes="application/xml". Server will probably complain if you don't send a file with this content type. This may also be a possible cause for that "ORA-31011: XML parsing failed" message, together with the double encoding (server is expecting XML in the document but finds another base64 string).
From SOAPUI everything sending ok with Enable MTOM settings
When using MTOM, your file is not encoded within the SOAP message as text, but it's attached as binary next to it, and you get references to that part of the message. See an explanation here: How does MTOM work?
Your document element might change to something like:
<document>
<inc:Include href="cid:123456789" xmlns:inc="http://www.w3.org/2004/08/xop/include"/>
</document>
where 123456789 is a reference to the content id in the multipart message.
Does your call work from SoapUI only if you enable MTOM? Have you tried sending a base64 encoded file string within the SOAP message using SoapUI?
If your call only works with MTOM then you have a problem, because I'm not sure zeep can handle it out of the box.
The documentation (https://docs.python-zeep.org/en/master/attachments.html) mentions only a multipart response and how you can read the file from the response, but says nothing about making requests. See for example these items:
https://github.com/mvantellingen/python-zeep/issues/599
https://github.com/mvantellingen/python-zeep/pull/314
https://github.com/remaudcorentin-dev/python-zeep-adv
The last project might help you with some code samples (https://github.com/remaudcorentin-dev/python-zeep-adv/blob/master/src/zeep/transport_with_attach.py) but do consider the caveat:
This has been developed for a specific usage and this code should probably not be used (has it) for other puposes.
(or at your own risks ;) )
So it seems you might have to build your own multipart request from scratch or from that sample in the project.
[...] and how debug sending requests?
You might use the HistoryPlugin just to see what messages get exchanged between your client and server, but since you might need to see all of the request, I suggest Wireshark, TcpMon (old, defunct, but still useful), or SoapUI with TcpMon.
This might not be the answer you are looking for, but hope that at least it leaves you more equipped in figuring out how to make the call. Zeep unfortunately is a small fish client in a large pond of WS specifications.
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'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
Ok there has been some confusion in what I am trying to do so I am doing this over again. I am looking to write a script to run against my inbox that will give me the From Address, Subject, and URL in the email body. The issue I am having is that the URL parsing of the script is pulling all URL's from the email and not just the one from the body. Here is an example
To: Tom#mail.com
From: Joe#test.com
Subject: Confirm you test score
Please go to the following URL to confirm your test score. WWW.test.com/confirmation
Thanks again for your input.
Signed
Joe
(Part of Joes signature has an image)
The URL for the image is
http://www.test.com/wp-content/uploads/_client_image/66-dcfc0fc8.png
I want my output to be
From: Joe#test.com
Subject: Confirm your test score
URL: WWW.test.com/confirmation
I get this instead
From: Joe#test.com
Subject: Confirem your test score
URL: WWW.test.com/confirmation, http://www.test.com/wp-content/uploads/_client_image/66-dcfc0fc8.png
And here is my script
import re
import mailbox
import urlparse
mbx=mailbox.mbox("Mail Box Path")
url_pattern = re.compile('''["']http://[^+]*?['"]''')
for k, m in mbx.iteritems():
print "From %s\n" % m['from']
print "Subject %s\n" % m['subject']
print "URL %s\n" % url_pattern.findall(m.as_string())
Signatures count as the body of the email - so you can't really separate them.
If you're sure there's only one link in the email that you care about, you could try just looking at only the first URL you match - but there isn't a (reliable) way to make sure that you're only interacting with the body of the email and not the signature as well.
Someone even wrote a paper on this - it's extremely difficult, especially when you can't control the format of the emails you're dealing with.