Question

I'm new to Python and trying to create a email sending script via socket communication but can't seem to sign it with the dkimpy lib. I tried a couple of examples on the web but all returned the same error when running dkim.sign:

File "C:\Python34\lib\re.py", line 196, in split return _compile(pattern,flags).split(string, maxsplit)
TypeError: expected string or buffer

Near as I can tell, the first variable in the dkim.sign function should be a string so I tried readlines () and even .as_string() just to be sure. I have checked the message and it seems RFC822 compliant. But I'll double check if anyone thinks that might be the problem. Without the dkim.sign it works perfectly ( minus any security like SPF/DKIM )

This is a snippet of the code I'm using:

f=open('mail.htm','r') 
text=MIMEText(f.read(),'html') 
headers = Parser().parse(open('mail.htm', 'r')) 
sender=headers['From'] 
receiver=headers['To'] 
subj=headers['Subject'] 
f.close() 
private_key = open('default.pem').read() 
headers = ['To', 'From', 'Subject'] 
sig = dkim.sign(text, 'default', '<mydomain.here>', private_key, include_headers=headers)

The parsed headers are also used as input to the socket sending script. I do have a dkim key for test purposes, but I do not think it even reaches that point.

Any insight?

EDIT: Ok, I just tried parsing the string ( instead of signing it ) with dkim.rfc822_parse from dkimpy lib and I get the following error:

return _compile(pattern, flags).split(string, maxsplit)
TypeError: can't use a bytes pattern on a string-like object

Am I reading this write or does it seem that the code is expecting a string but the pattern is in bytes?

FIXED: Odly enough I did not think to check the private_key. I manually created the key in Win so unbeknownst to me, windows added an invisible linebreak character that even vim or nano could not see. After removing it with MCEdit the program worked without a hitch. Thanks for the help :)

Was it helpful?

Solution

if I remember correctly, dkim.sign expects the full message source as parameter, but you are passing a MIMEText object.

try passing text.as_string() instead

sig = dkim.sign(text.as_string(), .... )

OTHER TIPS

python3 enforces a strong difference between processing bytes and string.

the easiest way I found to avoid conversion when using the dkim module is to stay in bytes, here is what I use:

from email.parser import BytesParser
import dkim

mail = BytesParser().parse (open('mail.eml', 'rb'))

print(dkim.verify( mail.as_bytes () ) )))

The "rb" is for opening the file in bytes mode.

Give it a try.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top