How to validate DKIM body hash manually? - email

This is an auto forwarded email.
I'm trying to verify the bh field as per rfc5322.
But the sha256 hash value received is not matching this value.
The message body is: for forwarded mail
Any suggestions to validate the bh= field correctly?
I have included some sample header field data. Please do explain (relaxed) canonical procedure too
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; t=1516798995;
s=jan2017; d=headsup.co.in; i=sender#headsup.co.in;
h=Date:From:To:Message-Id:Subject:MIME-Version:Content-Type; l=627;
bh=ODw8icD/S+4UGcXgR4ocNpxXDh4PolWtd1IUXjh0AUs=;
b=G2vTZ+uQ+krw49l+4aMnaeZjUvAJXPPRA8bvOhs3XZNbd2Ng+odB/F5PI3tRpdhr
C0CJA5KPv4VncP2V1PjNdkgKLjs1eTzLSaqmPjhhQDc8mWQRT0rzcPP3V9v6BeXF987
54Zns/QWtR+RbSacFXvUjyBEOlaWUVAmaVcqw5S8=
//Message: for forwarded mail
//Example Data
Date: Wed, 24 Jan 2018 18:33:08 +0530
From: sender <sender#headsup.co.in>
To: "receiver" <receiver#gmail.com>
Message-Id: <1612843d10d.d305604a24030.1212846966506749871#headsup.co.in>
Subject: Test Arc Seal
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_Part_76205_1329960269.1516798988558"
X-Priority: Medium
//Cannonicalization code (relaxed)
package canonicalization;
import java.io.IOException;
public class Canonicalization {
public String canonicalizeHeader(String name, String value) {
name = name.trim().toLowerCase();
value = value.replaceAll("\\s+", " ").trim();
return name + ":" + value;
}
public String canonicalizeBody(String body) {
if (body == null || "".equals(body)) {
return "\r\n";
}
body = body.replaceAll("[ \\t\\x0B\\f]+", " ");
body = body.replaceAll(" \r\n", "\r\n");
// The body must end with \r\n
if (!body.endsWith("\r\n")) {
return body + "\r\n";
}
// Remove trailing empty lines ...
while (body.endsWith("\r\n\r\n")) {
body = body.substring(0, body.length() - 2);
}
return body;
}
public static void main(String[] args) {
Canonicalization obj=new Canonicalization();
System.out.println(obj.canonicalizeHeader("Date"," Wed, 24 Jan 2018 18:33:08 +0530"));
System.out.println(obj.canonicalizeHeader("From"," sender <sender#headsup.co.in>"));
System.out.println(obj.canonicalizeHeader("To"," \"receiver\" <receiver#gmail.com>"));
System.out.println(obj.canonicalizeBody("for forwarded mail"));
}
}

You don't provide any code to illustrate how you are attempting to verify the body hash, but most likely you are incorrectly canonicalizing the input fed to the hashing function.

The code works fine for emails sent in plaintext format (Content-Type: text/plain;)
But by default, emails are sent by Rich Text Format (Content-Type: multipart/alternative;), hence the body hashes did not match

Related

Delphi/Indy 10 - Sending a text or HTML email with attachments adds an attachment for the text (body) itself

For years, we've been using Indy 10 to send emails (text, not HTML) with one or more PDF attached to it and we never had any problem.
Recently (maybe since Tokyo release 3 ?), our customers noticed that the text part of the email (body) is now an attachment and not part of the email itself.
I've searched the Internet for solutions, and everything I tested did not fix this problem.
I tried some of the solutions proposed on StackOverflow by Remy Lebeau with no success.
Here's the code (based on a post found on StackOverflow)
procedure TForm1.btnSendEmailClick(Sender: TObject);
var
smtp : TIdSMTP;
msg : TidMessage;
builder: TIdMessageBuilderHtml;
begin
msg := TidMessage.Create(nil);
try
builder := TIdMessageBuilderHtml.Create();
try
// FIsBodyHtml IS FALSE
if FIsBodyHtml then begin
builder.Html.Text := edText.Lines.Text;
builder.HtmlCharSet := 'utf-8';
builder.HtmlContentTransfer := 'quoted-printable';
end else begin
builder.PlainText.Text := edText.Lines.Text;;
builder.PlainTextCharSet := 'utf-8';
builder.PlainTextContentTransfer := 'quoted-printable';
end;
// Add attached file here
if (edFile.Text <> '') and FileExists(edFile.Text) then begin
builder.Attachments.Add(edFile.Text);
end;
builder.FillMessage(msg);
finally
builder.Free;
end;
msg.From.Name := 'From name here';
msg.From.Address := 'From email address here';
msg.Subject := edSubject.Text;
msg.Recipients.EmailAddresses := edEMail.Text;
// msg.CCList.EmailAddresses := CCAddresses;
// msg.BccList.EmailAddresses := BCCAddresses;
smtp := TIdSMTP.Create(nil);
try
smtp.Host := 'Host IP here';
// Smtp.UseTLS := utNoTLSSupport;
smtp.Port := 25;
// smtp.Username := '';
// smtp.Password := '';
// smtp.AuthType := satDefault;
smtp.Connect();
try
smtp.Send(msg);
finally
smtp.Disconnect;
end;
finally
smtp.Free();
end;
finally
msg.Free();
end;
ShowMessage('EMail with attachment sent.');
end;
RAW data BEFORE our service provider changed something :
X-Spam-Flag: NO
X-Envelope-From: stephans#xys.com
Return-Path: <stephans#xyz.com>
Received: from alt44.smtp-out.videotron.ca (alt44.smtp-out.videotron.ca [23.233.128.31])
by mail124c7.megamailservers.com (8.14.9/8.13.1) with ESMTP id w8IE2EaJ031620
for <stephans#xyz.com>; Tue, 18 Sep 2018 10:02:16 -0400
Received: from STEPHANS (99.99.99.99])
by Videotron with SMTP
id 2GZxgRaQACk662GZygKZJC; Tue, 18 Sep 2018 10:02:14 -0400
Message-ID: <0575a0d8ec54a7560be55a121df5deb7#smtp.videotron.ca>
X-Authority-Analysis: v=2.3 cv=I/dLuuog c=1 sm=1 tr=0
a=dE52as2XWJrk6k5j72Z8kA==:117 a=dE52as2XWJrk6k5j72Z8kA==:17
a=9DvhAHx2yrWFMPxQWpQA:9 a=ddwX9jWfLaJL_gwCi7EA:9 a=QEXdDO2ut3YA:10
a=x4g3fk4yahj5Vy8AyNEA:9 a=n3BslyFRqc0A:10 a=QGevMSd5eboA:10
From: "Stephan St-Denis" <stephans#xyz.com>
Subject: Sending an email with an attachment
To: stephans#xyz.com
Content-Type: multipart/mixed; boundary="sYOn6pS43NerAC6V2swiiWL68DI9=_SoRR"
MIME-Version: 1.0
Date: Tue, 18 Sep 2018 10:02:11 -0400
X-CMAE-Envelope: MS4wfKOiVw8oDz+nXCTnbMSWSKyXaMU478wM3VDSWQBABhzflbVLGHq70qeoq1ROGHLKj2lDQPx1LLDrcmvbcOtrdhj4j8xx2kLFmh3LfsDxgKpXpd44Lyvy
UHG4KDKHPNZy4UAAlgA05WwJ7eshsOWamzFhqA3QrXuliQNQVttLQNbhbjg2fqOR387/8VrwqftGFg==
X-CTCH-Spam: Unknown
X-CTCH-VOD: Unknown
X-CTCH-RefID: str=0001.0A020201.5BA10569.0015,ss=1,re=0.000,recu=0.000,reip=0.000,vtr=str,vl=0,cl=1,cld=1,fgs=0
X-CSC: 0
X-CHA: v=2.3 cv=TIBrtWta c=1 sm=1 tr=0 a=C7+rQaujYuxIIavLKnSTDg==:117
a=dE52as2XWJrk6k5j72Z8kA==:17 a=dueAcN81E1cA:10 a=JBFolyDoGHsA:10
a=9DvhAHx2yrWFMPxQWpQA:9 a=ddwX9jWfLaJL_gwCi7EA:9 a=QEXdDO2ut3YA:10
a=x4g3fk4yahj5Vy8AyNEA:9 a=n3BslyFRqc0A:10 a=QGevMSd5eboA:10
X-WHL: LR
X-EsetId: 37303A298E2AB560627366
This is a multi-part message in MIME format
--sYOn6pS43NerAC6V2swiiWL68DI9=_SoRR
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline;filename="Attachment"
This is the text that will be sent along with the attached file. This =
email is in text only format and not HTML.
The text should not be attached but should be part of the email.
--sYOn6pS43NerAC6V2swiiWL68DI9=_SoRR
Content-Type: application/pdf;
name="Embarcadero.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Embarcadero.pdf"
Content-ID: <Embarcadero.pdf>
JVBERi0xLjYKJf////8gd3d3LnN5bmFjdGlzLmNvbQoxIDAgb2JqCjw8Ci9DcmVhdGlvbkRhdGUo
RDoyMDE3MDIxNDE2MjAyMykKL1RpdGxlKENhc19kZV90ZXN0X0NBMS5wZGYpCi9BdXRob3IoTWFj
Q3JhemVlIEluYy4pCi9Qcm9kdWNlcihQREZCb3ggdmVyc2lvbiBpbnRlcm5lIExQQykKL0NyZWF0
b3IoTGVzIFByb2dpY2llbHMgQ29uY2VwdCBpbmMuKQo+PgplbmRvYmoKNSAwIG9iago8PAovTGVu
Z3RoIDMyNTcKPj4Kc3RyZWFtCkJUCi9GMCAxMiBUZgowIDAgMCByZwowIFRj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ZG9iago5IDAgb2JqCjw8Ci9UeXBlL0NhdGFsb2cKL1BhZ2VzIDIgMCBSCj4+
CmVuZG9iagoyIDAgb2JqCjw8Ci9UeXBlL1BhZ2VzCi9LaWRzWwo0IDAgUgpdCi9Db3VudCAxCi9S
ZXNvdXJjZXMgMyAwIFIKPj4KZW5kb2JqCjMgMCBvYmoKPDwKL1Byb2NTZXRbL1BERi9UZXh0L0lt
YWdlQ10KL0ZvbnQ8PAovRjAgOCAwIFIKPj4KPj4KZW5kb2JqCnhyZWYKMCAxMAowMDAwMDAwMDAw
IDY1NTM1IGYNCjAwMDAwMDAwMzIgMDAwMDAgbg0KMDAwMDAwNDI4MyAwMDAwMCBuDQowMDAwMDA0
MzU3IDAwMDAwIG4NCjAwMDAwMDM1MjIgMDAwMDAgbg0KMDAwMDAwMDIxMyAwMDAwMCBuDQowMDAw
MDAzNjA3IDAwMDAwIG4NCjAwMDAwMDM5MTEgMDAwMDAgbg0KMDAwMDAwNDA2MiAwMDAwMCBuDQow
MDAwMDA0MjM1IDAwMDAwIG4NCnRyYWlsZXIKPDwKL1NpemUgMTAKL1Jvb3QgOSAwIFIKL0luZm8g
MSAwIFIKL0lEWyg0Mjc4MDY4MDhzZWVkKSg0Mjc4MDY4MDhzZWVkKV0KPj4Kc3RhcnR4cmVmCjQ0
MjYKJSVFT0YK
--sYOn6pS43NerAC6V2swiiWL68DI9=_SoRR--
RAW data AFTER our service provider changed something
X-Spam-Flag: NO
X-Envelope-From: stephans#xyz.com
Return-Path: <stephans#xyz.com>
Received: from alt14.smtp-out.videotron.ca (alt14.smtp-out.videotron.ca [135.19.0.27])
by mail141c7.megamailservers.com (8.14.9/8.13.1) with ESMTP id w8JCvhOr015926
for <stephans#xyz.com>; Wed, 19 Sep 2018 08:57:45 -0400
Received: from STEPHANS ([99.99.99.99])
by Videotron with SMTP
id 2c34gzZ4bMdc62c35g1R7X; Wed, 19 Sep 2018 08:57:43 -0400
Message-ID: <5283e5cb2949102f2e22f509477dacaa#smtp.videotron.ca>
X-Authority-Analysis: v=2.3 cv=PoG9kTE3 c=1 sm=1 tr=0
a=dE52as2XWJrk6k5j72Z8kA==:117 a=dE52as2XWJrk6k5j72Z8kA==:17
a=9DvhAHx2yrWFMPxQWpQA:9 a=PyNp0P9dkJ191ZjJjSMA:9 a=ddwX9jWfLaJL_gwCi7EA:9
a=QEXdDO2ut3YA:10 a=x4g3fk4yahj5Vy8AyNEA:9 a=n3BslyFRqc0A:10 a=QGevMSd5eboA:10
From: "Stephan St-Denis" <stephans#xyz.com>
Subject: Sending an email with an attachment
To: stephans#xyz.com
Content-Type: multipart/mixed; boundary="2oubkSu12F4FBVsrQ1qmkA=_rIo3IvFYNM"
MIME-Version: 1.0
Date: Wed, 19 Sep 2018 08:57:42 -0400
X-CMAE-Envelope: MS4wfBPFtECskEptewv8r0bLuVgVpcybKuamQgK0q+veOE3mDcPmuU0j2BlwRMolPNl4KeDVRtyCVMVmkK8N5jufk8voKnE1l6SnBAVceHp6p6Ohg6KTOIp1
srRHBcfqKq4iTOHzsbt4HfC5vzAuQXm6H3d2pHYX2JNz8N1Pq6ze3mdvvacTtuYNEbvI0Ny8ev9LrA==
X-CTCH-Spam: Unknown
X-CTCH-VOD: Unknown
X-CTCH-RefID: str=0001.0A02020C.5BA247CA.0005,ss=1,re=0.000,recu=0.000,reip=0.000,vtr=str,vl=0,cl=1,cld=1,fgs=0
X-CSC: 0
X-CHA: v=2.3 cv=feyDNXYF c=1 sm=1 tr=0 a=csAb9/S9F4eoTzVqV71Dmw==:117
a=dE52as2XWJrk6k5j72Z8kA==:17 a=WrA80cmexyYA:10 a=JBFolyDoGHsA:10
a=9DvhAHx2yrWFMPxQWpQA:9 a=PyNp0P9dkJ191ZjJjSMA:9 a=ddwX9jWfLaJL_gwCi7EA:9
a=QEXdDO2ut3YA:10 a=x4g3fk4yahj5Vy8AyNEA:9 a=n3BslyFRqc0A:10
a=QGevMSd5eboA:10
X-WHL: LR
X-EsetId: 37303A298E2AB560627264
This is a multi-part message in MIME format
--2oubkSu12F4FBVsrQ1qmkA=_rIo3IvFYNM
Content-Type: multipart/alternative;
boundary="DhsioUcQxViR3rGTk=_q17PSufSL3rps7M"
--DhsioUcQxViR3rGTk=_q17PSufSL3rps7M
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
An HTML viewer is required to see this message
--DhsioUcQxViR3rGTk=_q17PSufSL3rps7M
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
This is the text that will be sent along with the attached file. This =
email is in text only format and not HTML.
The text should not be attached but should be part of the email.
--DhsioUcQxViR3rGTk=_q17PSufSL3rps7M--
--2oubkSu12F4FBVsrQ1qmkA=_rIo3IvFYNM
Content-Type: application/pdf;
name="Embarcadero.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Embarcadero.pdf"
Content-ID: <Embarcadero.pdf>
JVBERi0xLjYKJf////8gd3d3LnN5bmFjdGlzLmNvbQoxIDAgb2JqCjw8Ci9DcmVhdGlvbkRhdGUo
RDoyMDE3MDIxNDE2MjAyMykKL1RpdGxlKENhc19kZV90ZXN0X0NBMS5wZGYpCi9BdXRob3IoTWFj
Q3JhemVlIEluYy4pCi9Qcm9kdWNlcihQREZCb3ggdmVyc2lvbiBpbnRlcm5lIExQQykKL0NyZWF0
b3IoTGVzIFByb2dpY2llbHMgQ29uY2VwdCBpbmMuKQo+PgplbmRvYmoKNSAwIG9iago8PAovTGVu
Z3RoIDMyNTcKPj4Kc3RyZWFtCkJUCi9GMCAxMiBUZgowIDAgMCByZwowIFRjCjE5Ljg0MyA3NjUu
MDAyIFRkCiggICAgPVJFTEVWRSBERSBUUkFOU0FDVElPTj0pIFRqCkVUCkJUCi9GMCAxMiBUZgow
IDAgMCByZwowIFRjCjE5Ljg0MyA3NTMuMDk3IFRkCiggICAgID09VFJBTlNBQ1RJT04gUkVDT1JE
PT0pIFRqCkVUCkJUCi9GMCAxMiBUZgowIDAgMCByZ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BERi9UZXh0L0lt
YWdlQ10KL0ZvbnQ8PAovRjAgOCAwIFIKPj4KPj4KZW5kb2JqCnhyZWYKMCAxMAowMDAwMDAwMDAw
IDY1NTM1IGYNCjAwMDAwMDAwMzIgMDAwMDAgbg0KMDAwMDAwNDI4MyAwMDAwMCBuDQowMDAwMDA0
MzU3IDAwMDAwIG4NCjAwMDAwMDM1MjIgMDAwMDAgbg0KMDAwMDAwMDIxMyAwMDAwMCBuDQowMDAw
MDAzNjA3IDAwMDAwIG4NCjAwMDAwMDM5MTEgMDAwMDAgbg0KMDAwMDAwNDA2MiAwMDAwMCBuDQow
MDAwMDA0MjM1IDAwMDAwIG4NCnRyYWlsZXIKPDwKL1NpemUgMTAKL1Jvb3QgOSAwIFIKL0luZm8g
MSAwIFIKL0lEWyg0Mjc4MDY4MDhzZWVkKSg0Mjc4MDY4MDhzZWVkKV0KPj4Kc3RhcnR4cmVmCjQ0
MjYKJSVFT0YK
--2oubkSu12F4FBVsrQ1qmkA=_rIo3IvFYNM--
We have the same sort of problem with Microsoft Mail. It is caused by the "Content-Disposition: inline" line in the text part which causes MS Mail to show the text part as a downloadable attachment. Removing the Content-Disposition line fixes this but requires you to modify TIdMessageClient.SendBody. Frankly I think MS Mail is to blame.

SMTP mail server (sendgrid) error on submission

I have an app that sends an email with image attachments thru an SMTP server (sendgrid).
When the application launches it initializes a Socket connection and authenticates the user(application. I see the following message returned from Sendgrid
SG ESMTP service ready at<foo..sendgrid.net
and I also get a successful authentication returned.
However, on sending an email I get the following 3 errors:
error 1 550 Unauthenticated senders not allowed
error 2 503 Must have sender before recipient
error 3 503 Must have valid receiver and originator
So this suggests to me that I must change the order of sender and recipient in my SMTP module. Internally I am taking an incoming ByteArray and converting to base64 string in order to send emails with attached files. So how would I change the following code excerpt?
writeUTFBytes ("MAIL FROM: <"+pFrom+">\r\n");
writeUTFBytes ("RCPT TO: <"+pDest+">\r\n");
writeUTFBytes ("DATA\r\n");
writeUTFBytes ("From: "+pFrom+"\r\n");
writeUTFBytes ("To: "+pDest+"\r\n");
This is the entire class I am using. I call authenticate just once after the class is initialized and then sendAttachedMail when sending email with image attachments. And when testing using a local SMTP server WITHOUT authentication, everything works fine(emails and image attachments sent)
package org.bytearray.smtp.mailer
{
import flash.events.ProgressEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import org.bytearray.smtp.crypto.MD5;
import org.bytearray.smtp.encoding.Base64;
import org.bytearray.smtp.events.SMTPEvent;
import org.bytearray.smtp.infos.SMTPInfos;
public class SMTPMailer extends Socket
{
private var sHost:String;
private var buffer:Array = new Array();
// regexp pattern
private var reg:RegExp = /^\d{3}/img;
// PNG, JPEG header values
private static const PNG:Number = 0x89504E47;
private static const JPEG:Number = 0xFFD8;
// common SMTP server response codes
// other codes could be added to add fonctionalities and more events
private static const ACTION_OK:Number = 0xFA;
private static const AUTHENTICATED:Number = 0xEB;
private static const DISCONNECTED:Number = 0xDD;
private static const READY:Number = 0xDC;
private static const DATA:Number = 0x162;
private static const BAD_SEQUENCE:Number = 0x1F7;
public function SMTPMailer ( pHost:String, pPort:int)
{
super ( pHost, pPort );
sHost = pHost;
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler,false,0,true);
}
public function reset():void{
removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
/*
* This method lets you authenticate, just pass a login and password
*/
public function authenticate ( pLogin:String, pPass:String ):void
{
writeUTFBytes ("EHLO "+sHost+"\r\n");
writeUTFBytes ("AUTH LOGIN\r\n");
writeUTFBytes (Base64.encode64String (pLogin)+"\r\n");
writeUTFBytes (Base64.encode64String (pPass)+"\r\n");
flush();
}
/*
* This method is used to send emails with attached files and HTML
* takes an incoming Bytearray and convert it to base64 string
* for instance pass a JPEG ByteArray stream to get a picture attached in the mail ;)
*/
public function sendAttachedMail ( pFrom:String, pDest:String, pSubject:String, pMess:String, pByteArray:ByteArray, pFileName:String ) :void
{
try {
writeUTFBytes ("HELO "+sHost+"\r\n");
writeUTFBytes ("MAIL FROM: <"+pFrom+">\r\n");
writeUTFBytes ("RCPT TO: <"+pDest+">\r\n");
writeUTFBytes ("DATA\r\n");
writeUTFBytes ("From: "+pFrom+"\r\n");
writeUTFBytes ("To: "+pDest+"\r\n");
writeUTFBytes ("Date : "+new Date().toString()+"\r\n");
writeUTFBytes ("Subject: "+pSubject+"\r\n");
writeUTFBytes ("Mime-Version: 1.0\r\n");
var md5Boundary:String = MD5.hash ( String ( getTimer() ) );
writeUTFBytes ("Content-Type: multipart/mixed; boundary=------------"+md5Boundary+"\r\n");
writeUTFBytes("\r\n");
writeUTFBytes ("This is a multi-part message in MIME format.\r\n");
writeUTFBytes ("--------------"+md5Boundary+"\r\n");
writeUTFBytes ("Content-Type: text/html; charset=UTF-8; format=flowed\r\n");
writeUTFBytes("\r\n");
writeUTFBytes (pMess+"\r\n");
writeUTFBytes ("--------------"+md5Boundary+"\r\n");
writeUTFBytes ( readHeader (pByteArray, pFileName) );
writeUTFBytes ("Content-Transfer-Encoding: base64\r\n");
writeUTFBytes ("\r\n");
var base64String:String = Base64.encode64 ( pByteArray, true );
writeUTFBytes ( base64String+"\r\n");
writeUTFBytes ("--------------"+md5Boundary+"-\r\n");
writeUTFBytes (".\r\n");
flush();
} catch ( pError:Error )
{
trace("Error : Socket error, please check the sendAttachedMail() method parameters");
trace("Arguments : " + arguments );
}
}
/*
* This method is used to send HTML emails
* just pass the HTML string to pMess
*/
public function sendHTMLMail ( pFrom:String, pDest:String, pSubject:String, pMess:String ):void
{
try
{
writeUTFBytes ("HELO "+sHost+"\r\n");
writeUTFBytes ("MAIL FROM: <"+pFrom+">\r\n");
writeUTFBytes ("RCPT TO: <"+pDest+">\r\n");
writeUTFBytes ("DATA\r\n");
writeUTFBytes ("From: "+pFrom+"\r\n");
writeUTFBytes ("To: "+pDest+"\r\n");
writeUTFBytes ("Subject: "+pSubject+"\r\n");
writeUTFBytes ("Mime-Version: 1.0\r\n");
writeUTFBytes ("Content-Type: text/html; charset=UTF-8; format=flowed\r\n");
writeUTFBytes("\r\n");
writeUTFBytes (pMess+"\r\n");
writeUTFBytes (".\r\n");
flush();
} catch ( pError:Error )
{
trace("Error : Socket error, please check the sendHTMLMail() method parameters");
trace("Arguments : " + arguments );
}
}
/*
* This method automatically detects the header of the binary stream and returns appropriate headers (jpg, png)
* classic application/octet-stream content type is added for different kind of files
*/
private function readHeader ( pByteArray:ByteArray, pFileName:String ):String
{
pByteArray.position = 0;
var sOutput:String = null;
if ( pByteArray.readUnsignedInt () == SMTPMailer.PNG )
{
sOutput = "Content-Type: image/png; name="+pFileName+"\r\n";
sOutput += "Content-Disposition: attachment filename="+pFileName+"\r\n";
return sOutput;
}
pByteArray.position = 0;
if ( pByteArray.readUnsignedShort() == SMTPMailer.JPEG )
{
sOutput = "Content-Type: image/jpeg; name="+pFileName+"\r\n";
sOutput += "Content-Disposition: attachment filename="+pFileName+"\r\n";
return sOutput;
}
sOutput = "Content-Type: application/octet-stream; name="+pFileName+"\r\n";
sOutput += "Content-Disposition: attachment filename="+pFileName+"\r\n";
return sOutput;
}
// check SMTP response and dispatch proper events
// Keep in mind SMTP servers can have different result messages the detection can be modified to match some specific SMTP servers
private function socketDataHandler ( pEvt:ProgressEvent ):void
{
var response:String = pEvt.target.readUTFBytes ( pEvt.target.bytesAvailable );
buffer.length = 0;
var result:Array = reg.exec(response);
while (result != null)
{
buffer.push (result[0]);
result = reg.exec(response);
}
var smtpReturn:Number = buffer[buffer.length-1];
var smtpInfos:SMTPInfos = new SMTPInfos ( smtpReturn, response );
if ( smtpReturn == SMTPMailer.READY )
dispatchEvent ( new SMTPEvent ( SMTPEvent.CONNECTED, smtpInfos ) );
else if ( smtpReturn == SMTPMailer.ACTION_OK && (response.toLowerCase().indexOf ("queued") != -1 || response.toLowerCase().indexOf ("accepted") != -1 ||
response.toLowerCase().indexOf ("qp") != -1) ) dispatchEvent ( new SMTPEvent ( SMTPEvent.MAIL_SENT, smtpInfos ) );
else if ( smtpReturn == SMTPMailer.AUTHENTICATED )
dispatchEvent ( new SMTPEvent ( SMTPEvent.AUTHENTICATED, smtpInfos ) );
else if ( smtpReturn == SMTPMailer.DISCONNECTED )
dispatchEvent ( new SMTPEvent ( SMTPEvent.DISCONNECTED, smtpInfos ) );
else if ( smtpReturn == SMTPMailer.BAD_SEQUENCE )
dispatchEvent ( new SMTPEvent ( SMTPEvent.BAD_SEQUENCE, smtpInfos ) );
else if ( smtpReturn != SMTPMailer.DATA )
dispatchEvent ( new SMTPEvent ( SMTPEvent.MAIL_ERROR, smtpInfos ) );
}
}
}
So this suggests to me that I must change the order of sender and recipient in my SMTP module.
The order of your commands is correct. Instead, you should look at the first error message for the real cause of the problem:
error 1 550 Unauthenticated senders not allowed
This tells you that the server requires authentication from the sender, i.e. use of the SMTP AUTH command with user credentials. Attempts to send mail from an unauthenticated sender will be rejected. As such, if MAIL FROM fails, then RCPT TO fails. If RCPT TO fails, then DATA fails. And so on.
Use the SMTP EHLO command to discover the AUTH schemes (and other capabilities) that the server supports, and then send the appropriate AUTH command before sending MAIL FROM.
UPDATE: sorry, I had not examined your class carefully. You already have an authenticate method and it does what it should. So, apparently, while you think that you're calling it, either it isn't getting called, or it fails.
So check carefully that the connection you're authenticating in and the connection you're sending mail in are actually the same connection, and you are not maybe unwittingly re-creating a new, unauthenticated connection.
Also, you really need to check the results of the operations you conduct - in this case, the authentication. Is it really successful?
Old answer
From your example and what little documentation I found, you need - or at least appear to need - two authentications. Probably with the same username and password.
The first one you're doing right, it is the 'XML socket connection' that gets you to the SMTP layer.
Now you need the second authentication. Otherwise all commands will fail and the errors will pancake one into the other, while the 'real' error, as Steffen Ulrich noticed, is the first.
writeUTFBytes ("HELO "+sHost+"\r\n");
// Inner authentication
writeUTFBytes ("AUTH LOGIN\r\n");
writeUTFBytes (Base64.encode64 (username) + "\r\n");
writeUTFBytes (Base64.encode64 (password) + "\r\n");
// HERE you really should read the stream and ensure it says
// "Authentication OK" -- or something to that effect.
writeUTFBytes ("MAIL FROM: <"+pFrom+">\r\n");
This line indicates the error:
error 1 550 Unauthenticated senders not allowed
May it be that you have to register your sender email address in sendgrid first? See https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/senders.html#-Create-Your-Sender-Identity
If you have already done this, what does the email activity page tells you? (See https://sendgrid.com/docs/User_Guide/email_activity.html)

parsing email with mime4j

I encountered a problem when parsing email with mime4j.
The email has an attachment, and I use MimeStreamParser to parse it.
The parser does not call startMultipart method at all. Instead, it only calls body method once, and the BodyDescriptor is "text/plain".
I do not know the root of this problem, the email format or my program?
Here is my test program:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.james.mime4j.*;
import org.apache.james.mime4j.dom.BinaryBody;
import org.apache.james.mime4j.dom.Body;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Header;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.dom.MessageBuilder;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.dom.TextBody;
import org.apache.james.mime4j.dom.address.Mailbox;
import org.apache.james.mime4j.dom.address.MailboxList;
import org.apache.james.mime4j.dom.field.AddressListField;
import org.apache.james.mime4j.dom.field.ContentTypeField;
import org.apache.james.mime4j.dom.field.DateTimeField;
import org.apache.james.mime4j.dom.field.UnstructuredField;
import org.apache.james.mime4j.field.address.AddressFormatter;
import org.apache.james.mime4j.message.BodyPart;
import org.apache.james.mime4j.message.MessageImpl;
import org.apache.james.mime4j.message.DefaultMessageBuilder;
import org.apache.james.mime4j.message.SimpleContentHandler;
import org.apache.james.mime4j.parser.ContentHandler;
import org.apache.james.mime4j.parser.MimeStreamParser;
import org.apache.james.mime4j.stream.BodyDescriptor;
import org.apache.james.mime4j.stream.Field;
import org.apache.james.mime4j.stream.MimeConfig;
public class TestClass extends SimpleContentHandler{
public static void main(String[] args) throws MimeException, IOException {
ContentHandler handler = new TestClass();
MimeConfig config = new MimeConfig();
MimeStreamParser parser = new MimeStreamParser(config);
parser.setContentHandler(handler);
InputStream instream = new FileInputStream("mail/testuser1");
try {
parser.parse(instream);
} finally {
instream.close();
}
}
#Override
public void headers(Header arg0) {
// TODO Auto-generated method stub
System.out.println("headers args: "+arg0);
}
#Override
public void body(BodyDescriptor bd, InputStream is) {
// TODO Auto-generated method stub
System.out.println("body descriptor: "+bd);
}
public void startMessage(){
System.out.println("startMessage");
}
public void endMessage(){
System.out.println("endMessage");
}
public void startBodyPart(){
System.out.println("startBodyPart");
}
public void endBodyPart() {
System.out.println("endBodyPart");
}
public void preamble(InputStream is){
System.out.println("preamble");
}
public void epilogue(InputStream is) {
System.out.println("epilogue");
}
public void startMultipart(BodyDescriptor bd){
System.out.println("startMultipart");
}
public void endMultipart() {
System.out.println("endMultipart");
}
public void raw(InputStream is) {
System.out.println("raw");
}
}
Here is a part of my email file:
From MAILER_DAEMON Wed Aug 21 19:24:53 2013
Date: Wed, 21 Aug 2013 19:24:53 +0800
From: Mail System Internal Data <MAILER-DAEMON#mail.abc.com>
Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
Message-ID: <1377084293#mail.abc.com>
X-IMAP: 1377072167 0000000003
Status: RO
This text is part of the internal format of your mail folder, and is not
a real message. It is created automatically by the mail system software.
If deleted, important folder data will be lost, and it will be re-created
with the data reset to initial values.
From testuser2#abc.com Sat Aug 24 10:53:42 2013
Return-Path: <testuser2#abc.com>
X-Original-To: testuser1#abc.com
Delivered-To: testuser1#abc.com
Received: from shupc (unknown [192.168.75.130])
by mail.abc.com (Postfix) with SMTP id C0F5B1EFBC3
for <testuser1#abc.com>; Sat, 24 Aug 2013 10:53:42 +0800 (CST)
Message-ID: <7F1C30C9CB284CA594D01CBE210257D3#shupc>
From: "john" <testuser2#abc.com>
To: "smith" <testuser1#abc.com>
Subject: aaa
Date: Sat, 24 Aug 2013 10:53:42 +0800
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 6.00.2900.5512
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5512
X-UID: 3
Status: O
Content-Length: 386430
This is a multi-part message in MIME format.
------=_NextPart_000_000B_01CEA0B8.32903020
Content-Type: multipart/alternative;
boundary="----=_NextPart_001_000C_01CEA0B8.32903020"
------=_NextPart_001_000C_01CEA0B8.32903020
Content-Type: text/plain;
charset="gb2312"
Content-Transfer-Encoding: base64
dGVzdCBhYSBiYiBjYw==
------=_NextPart_001_000C_01CEA0B8.32903020
Content-Type: text/html;
charset="gb2312"
Content-Transfer-Encoding: base64
PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv
L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu
dD0idGV4dC9odG1sOyBjaGFyc2V0PWdiMjMxMiI+DQo8TUVUQSBjb250ZW50PSJNU0hUTUwgNi4w
MC4yOTAwLjU1MTIiIG5hbWU9R0VORVJBVE9SPg0KPFNUWUxFPjwvU1RZTEU+DQo8L0hFQUQ+DQo8
Qk9EWSBiZ0NvbG9yPSNmZmZmZmY+DQo8RElWPjxGT05UIHNpemU9Mj50ZXN0IGFhIGJiIGNjPC9G
T05UPjwvRElWPjwvQk9EWT48L0hUTUw+DQo=
------=_NextPart_001_000C_01CEA0B8.32903020--
------=_NextPart_000_000B_01CEA0B8.32903020
Content-Type: application/octet-stream;
name="10112716229607.doc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="10112716229607.doc"
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAAFAAAAKAIAAAAAAAAA
EAAAKgIAAAEAAAD+////AAAAACMCAAAkAgAAJQIAACYCAAAnAgAA////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAcWAJBAAA8FK/AAAAAAAAEAAAAAAABgAArJ0CAA4AYmpianFQcVAAAAAAAAAAAAAAAAAAAAAA
AAAECBYAOBIDABM6AQATOgEA1gwBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w
The problem is with the sample email which not multipart. It contains, as inline text, a multipart email.
Remove the first headers ("FROM MAILER") and then make sure all lines following after Content-Type are indented (eg charset and boundary) by at least one whitespace character as required by the spec (RFC822 or later) or remove the linefeed. See example:
Change from :
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
to either:
Content-Type: multipart/mixed;
boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
or:
Content-Type: multipart/mixed; boundary="----=_NextPart_000_000B_01CEA0B8.32903020"
Alternatively, try a different message.
Use the following library based on mime4j:
email-mime-parser
The provided sample code takes care of email parsing and the resulting 'email' object provides convenience method for the solution of your problem :
ContentHandler contentHandler = new CustomContentHandler();
MimeConfig mime4jParserConfig = new MimeConfig();
BodyDescriptorBuilder bodyDescriptorBuilder = new DefaultBodyDescriptorBuilder();
MimeStreamParser mime4jParser = new MimeStreamParser(mime4jParserConfig,DecodeMonitor.SILENT,bodyDescriptorBuilder);
mime4jParser.setContentDecoding(true);
mime4jParser.setContentHandler(contentHandler);
InputStream mailIn = 'Provide email mime stream here';
mime4jParser.parse(mailIn);
Email email = ((CustomContentHandler) contentHandler).getEmail();

malformed email subject header when subject > 75 chars using codeigniter email lib

I'm getting some garble in my MIME headers when the subject is over 75 chars.
When the line break is encoded in the header there is an extra line break that is invalid.
Some email gateways are bouncing the email with a "Malformed MIME field: ?= =?utf-8?Q?SUBJECT?=" error.
Does anyone have any experience with utf-8 problems sending emails with CodeIgniter?
-snip-
Return-Path: ***
Subject: =?utf-8?Q?SUBJECT_LINE <--
?= <-- Problem in Subject header
=?utf-8?Q?SUBECT_LINE_2?= <--
To: ***
Reply-To: ***
-snip-
Update:
This has nothing to do with gmail smtp. I have rewritten the question in the hope that it will help someone out in the future.
Apparently this is a known issue, caused by Subject lines > 75 chars.
http://codeigniter.com/forums/viewthread/154493/P15/#925385
The fix was to change the email config like this:
$config['newline'] = "\r\n";
$config['crlf'] = "\n";
Since I myself had this exact problem I will share the solution here since the one shared does not work with version 2.2
Find this piece of code located in system/libraries/Email.php:365
public function subject($subject)
{
$subject = $this->_prep_q_encoding($subject);
$this->_set_header('Subject', $subject);
return $this;
}
With this one
public function subject($subject)
{
$subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
$this->_set_header('Subject', $subject);
return $this;
}

Writing an encrypted mail via Exchange Web Services

I would like to send an encrypted EMail Message with Exchange WEb Services using C#.
Is there any possibillity?
Thanks
Edit:
My Mail body encrypter:
public static byte[] encry(string body, ContentTyp typ, string to )
{
X509Certificate2 cert = GetMailCertificate(to);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
envelope.Encrypt(recipient);
//System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
return envelope.Encode();
}
Main
byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test#server.com");
EmailMessage msg1 = new EmailMessage(_server);
msg1.MimeContent = new MimeContent("UTF-8", con);
msg1.ToRecipients.Add("user#server.com");
msg1.InternetMessageHeaders = ??
msg1.Send();
If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.
Using the EWS Managed API, this can be done as follows:
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
EDIT:
You should add the standard headers like From, To, Date, Subject, etc. And the content-type.
Subject: Test
From: "sender" <sender#yourcompany.com>
To: "recipient" <recipient#othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m
Your encrypted body goes here
Just use a StringWriter put all that together. The result is your MIME body.