Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually signing an email with DKIM in Python

Tags:

python

email

dkim

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 :)

like image 646
alex.b Avatar asked Oct 01 '22 03:10

alex.b


1 Answers

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(), .... )
like image 150
Gryphius Avatar answered Oct 05 '22 22:10

Gryphius