IBM®
Skip to main content
    Country/region select      Terms of use
 
 
   
     Home      Products      Services & solutions      Support & downloads      My account     

developerWorks  >  Lotus  >  Forums & community  >  Best Practice Makes Perfect

Best Practice Makes Perfect

A collaboration with Domino developers about how to do it and how to get it right in Domino

This question has been asked in the forums a few times and I'm not sure it's ever been adequately answered, so I thought I would show some sample code to programmatically generate the MIME content for an email body containing an attachment read from disk.

The MIME has to be multi-part, with the text being one part and each attachment being a separate part. Plug in your values in place of the parts in red.

Set result = doc.CreateMIMEEntity("Body")
Dim hdr As NotesMimeHeader
Set hdr = result.CreateHeader("Subject")
Call hdr.SetHeaderValAndParams(|Subject|)
Set hdr = result.CreateHeader("MIME-Version")
Call hdr.SetHeaderValAndParams(|1.0|)
' create multipart MIME
result.Preamble = |This is a multipart message in MIME format.
|

Dim tmp1 As NotesMimeEntity
Set tmp1 = result.CreateChildEntity( )
' text entity, encoding type ENC_NONE
Dim stream As NotesStream
Dim session As New NotesSession
Set stream = session.CreateStream
stream.WriteText |Message text in HTML|
tmp1.SetContentFromText stream, "text/html", ENC_NONE
' create another MIME part for the attachment. (repeat as needed)
Set tmp1 = result.CreateChildEntity( )
Set hdr = tmp1.CreateHeader("Content-Disposition")
Call hdr.SetHeaderValAndParams(|attachment; filename="filename of file to attach"|)
' application entity, encoding type ENC_IDENTITY_BINARY
Set stream = session.CreateStream
stream.Open "filepath of file to attach", "binary"
tmp1.SetContentFromBytes stream, "application/octet-stream", ENC_BINARY
tmp1.EncodeContent ENC_BASE64
' end of code to repeat per attachment.
Call doc.CloseMIMEEntities(True, "Body")

Andre Guirard | 28 May 2008 10:22:00 AM ET | Home, Plymouth, MN, USA | Comments (25)


 Comments

1) Creating a MIME email with an attachment
Karsten Lehmann | 5/28/2008 12:03:37 PM

Thanks! Do you have a sample that generates a HTML email with embedded images?

2) re: embedded images
Andre Guirard | 5/28/2008 12:33:43 PM

The free download that accompanies this article: { Link }

contains a form that lets you enter some rich text manually, and automatically generates the source code to create the same content in MIME. Try that with an embedded image, and you'll see the source contains the hardcoded base64 data. If you wanted to get the image from a file instead, you'd do something very similar to the above.

3) Creating a MIME email with an attachment
sushant likhar | 5/28/2008 1:07:32 PM

what if a user wants to implement it in R5 . I guess there are undocumented class which still work.

Thanks

Sushant

4) Creating a MIME email with an attachment
Andre Guirard | 5/28/2008 6:12:05 PM

sushant, I don't know offhand whether it can be done in R5 -- I'm guessing probably not, since I don't know how you would insert the binary file data without NotesStream, which wasn't available until 6.0. If there are undocumented classes to do this, then I'm not aware of them. I'm sorry you have to use R5.

5) Thow an error msg Lotus Ver 6.5.6
Subhankar | 5/29/2008 8:32:58 AM

Hi Andre,

Pls note that I hv a problem with OLE automation in VFP trwoing an error msg that Data Type Mismatch

the code I written is quite similar to VB.NET. here it is:

Session = CreateObject("Lotus.NotesSession")

Session.Initialize()

Session.ConvertMime=.F.

Server= Session.GetEnvironmentString( "MailServer",.T.)

MaildbName=Session.GetEnvironmentString( "MailFile",.T.)

Maildb = Session.getdatabase(Server, MaildbName )

MailDoc = Maildb.CREATEDOCUMENT

result=MailDoc.CreateMIMEEntity("Body")

hdr=result.CreateHeader("Content-Type")

hdr.SetHeaderVal("multipart/mixed")

hdr=result.CreateHeader("Body")

hdr.SetHeaderVal("MIME Messages")

hdr=result.CreateHeader("To")

hdr.SetHeaderVal(Allt(Thisform.txtMailSend.Value))

tmp1=result.createChildEntity( )

This portion I hv recvd an error msg that "Data Type Mismatch"

Will you please kind enough what am I missing here

best regards

Subhankar

6) Creating a MIME email with an attachment
Ernie Mercer | 5/29/2008 1:10:38 PM

Andre, your link in @2 is invalid (it returns a 404 error).

7) Creating a MIME email with an attachment
Andre Guirard | 5/29/2008 9:00:37 PM

@6, Really? It works OK for me. Perhaps it was a server glitch.

8) Creating a MIME email with an attachment
Mael | 5/30/2008 8:46:47 AM

@6 - Substitute "{ Link } with "{ Link }

Andre, what icon will be displayed with the attachment? A generic icon or the associated application's icon?

Many thanks

9) Creating a MIME email with an attachment
Mael | 5/30/2008 8:52:00 AM

I meant to write:

Substitute "drh02.eapps.com" with "www.eview.com"

10) Creating a MIME email with an attachment
Andre Guirard | 5/31/2008 1:19:39 PM

@mael, the same graphic you selected for the icon when you created it manually. If that's a custom image (stored in your bookmark.nsf), you have the option to store and install the image resource along with the toolbar button.

11) Creating a MIME email with an attachment
Mael | 6/2/2008 1:21:03 AM

Many thanks, Andre

12) Creating a MIME email with an attachment
Henning Heinz | 6/11/2008 11:03:05 AM

Thank you.

If I remember correctly I've had problems sending a message with an alternative part and an attachment. I think the secret is to start with a multipart/mixed and then the attachment as one child and the alternative part with a plain text and an html version of the message. The Notes client can do it, I failed miserably.

13) Creating a MIME email with an attachment
Jaime Bisgrove | 9/10/2008 1:50:50 PM

Andre,

Is there a way to have the image file attached rather than inline ? I was able to take binary data and apply it as you did to the Body of a document. What I would like to do is attach it to the document (ie $File). I am having an issue doing this as the data is in a stream and I am having a problem getting a handle to it as such.

Any ideas?

14) Creating a MIME email with an attachment
Jaime Bisgrove | 9/11/2008 10:03:46 AM

Andre,

I wanted to clarify my previous comment. The file I receive is an xml file that is sending the image as binary data. I used the example db you gave in @2. It worked well, but it embeds the image in the body of the document. I cannot use the technique above as it assumes I have a file to attach. Any recommendations or direction is appreciated.

Regards,

Jaime

15) Creating a MIME email with an attachment
Robert Pena | 7/30/2009 7:53:41 PM

Andre, in previous versions of Domino, you didn't have to specify the MIME-Version: 1.0 when creating a MIME email with an attachment. Now in 8.x it seems you do. Would this be a regression?

16) Creating a MIME email with an attachment
Andre Guirard | 7/31/2009 9:37:02 AM

@Robert, I don't know, but if it's broken a previously working app we could make a good case for changing it back, anyway. Would you go thru the support process on this?

17) Attachment from $File
Duvvuri D Prasad | 9/28/2009 1:08:01 PM

Andre,

my user just uploaded his attachment and i wanted to send it in the MIME email.. but the NotesStream is only reading the file from disk ? is there a way to tell it to read the content from $File ?

My only other option is to extract it and then attach it which i don't want to do..

Thanks.

18) Streaming attachments
Karsten Lehmann | 9/29/2009 1:22:52 AM

Streaming attachments (for upload and download) is a thing that is really missing in the Notes API. E.g. when you try to get an InputStream for an attachment in Java, the API internally first extracts the attachment to a temporary folder and then returns the stream of that file.

We implemented this function directly in Java using the C API (via JNI) and our own InputStream implementation, so it's also possible for IBM to add this improved functionality to the API code.

Please add this in Notes RNext - and also please add a way to upload an attachment (in a stream) via C API with compression. We could only find API methods that work without compression.

19) Complete path displayed
realm174 | 2/19/2010 12:40:35 PM

I just came across the code above, which is awesome, as I had no idea where to start with adding attachments. After a little bit of adjusting things to match my original code, I finally got it to work. So thank you very much!! I'm a lot closer to my solution. However, when I open the email in the Lotus client, the attachment shows part of the entire "original" path, ie:

c:\document and settings\xyz\Desktop\LotusNotes

The actual path and filename of the attachment is:

C:\Documents and Settings\xyz\Desktop\LotusNotes documentation\part1.pdf

So when I try to view and/or save the attachment, the whole thing is truncated as per the first path shown above. Is there any way to change that behavior?

I would be happy if it only showed "part1.pdf" as the filename for the attachment in the client.

Also, despite the incomplete path\filename, the file attached is still the proper one. If I save it under a pdf name, it's just fine.

thanks!!

20) Complete path displayed
realm174 | 2/19/2010 12:47:59 PM

Ahhh never mind... not enough coffee I guess.. I figured out my mistake. :)

21) message/rfc822
Petr Kriz | 3/24/2010 8:03:59 AM

Nice code, but I cant find out how to send another message as an attachment (Content-Type: message/rfc822). If I use application/octet-stream instead of message/rfc822, the message is included as attachment, but I need to define embedded message as rcf822. When message/rfc822 is used as content type than embedded message is empty. Any ideas? Thanks in advance.

22) Pesky error
Ben V | 7/27/2011 10:19:22 AM

I get the following error: "Character set conversion translation failure."

The error is raised at this line:

Call bodyChild.SetContentFromText (stream, "application/octet-stream", ENC_IDENTITY_BINARY)

The file I try to attach is a PDF file but changing the content-type to "application/pdf" doesn't change a thing. Also, I want to add severall attachments so the last eight lines or so are in a loop.

23) Mulitple Attachments
jie | 7/31/2011 9:55:54 AM

I'm using a code which is very similar to yours in C#. However when i have multiple attachments, only the first attachment gets attached correctly, the rest are in invalid format when you try to open them.

My code:

session.ConvertMime = false;

Domino.NotesStream stream = session.CreateStream();

stream.WriteText(mess, Domino.EOL_TYPE.EOL_ANY);

Domino.NotesMIMEEntity mimeBody = memo.CreateMIMEEntity("Body");

Domino.NotesMIMEEntity mimeHtml = mimeBody.CreateChildEntity(null);

Domino.NotesMIMEHeader header = mimeBody.CreateHeader("Subject");

//For the HTML part of the message

mimeHtml.SetContentFromText(stream, "text/html; charset=\"iso-8859-1\"", Domino.MIME_ENCODING.ENC_QUOTED_PRINTABLE);

stream.Close();

stream.Truncate();

//This is for looping through an arraylist with names of the files to be attached

if (file.Count > 0)

{

String fileName = "";

foreach (string i in file)

{

fileName =i.Substring(i.LastIndexOf("\\") + 1);

mimeHtml = mimeBody.CreateChildEntity(null);

header = mimeHtml.CreateHeader("Content-Type");

header.SetHeaderVal("multipart/mixed"); //related

header = mimeHtml.CreateHeader("Content-Disposition");

header.SetHeaderVal("attachment; filename=" + fileName);

header = mimeHtml.CreateHeader("Content-ID");

header.SetHeaderVal(fileName);

stream = session.CreateStream();

if (stream.Open(i, "binary"))

{

mimeHtml.SetContentFromBytes(stream, "application/octet-stream", Domino.MIME_ENCODING.ENC_IDENTITY_BINARY);

mimeHtml.EncodeContent(MIME_ENCODING.ENC_BASE64);

}

stream.Close();

stream.Truncate();

}

}

Please help.

24) Fixed that for you...
Doug Finner | 3/16/2012 7:37:42 AM

First of all, a HUGE thank you for posting this code. I'm just learning how to do this MIME coding and this example pulls together most of the bits needed to create a formatted email. Thank you!

Second, I had to tweak two lines to get the code to work in my 6.5.4 environment.

Call tmp1.SetContentFromText(stream, "text/html", ENC_NONE)

Call tmp1.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)

25) Improper Encoding, HELP
David K | 2/3/2016 10:34:47 PM

I executed the above code and the email looks great, formatwise, but when I try to put the following line in, the Lotuscript panel raises an error for ENC_BINARY.

tmp1.SetContentFromBytes stream, "application/octet-stream", ENC_BINARY.

So I changed it to ENC_IDENTITY_BINARY and while the Lotuscript panel likes it, I still cannot open the files that show up in the email. Message says they were corrupted or not encoded properly.

here it the relevant portion of the code, and the GetSystemTempFolder resolves to C:\Windows\Temp. Running on Domino 9

If doctemp.HasEmbedded Then

Set attachlist = doctemp.GetFirstItem("AttachNames")

ForAll value In attachList.values

FilePath$ = getSystemTempFolder +"\" + value

Set object = doctemp.GetAttachment(value)

Call object.ExtractFile(Filepath$)

Set tmp1 = result.CreateChildEntity( )

Set hdr = tmp1.CreateHeader("Content-Disposition")

Call hdr.SetHeaderValAndParams(|attachment; filename="|+ value +|"|)

Set stream = session.CreateStream

stream.Open FilePath$, "binary"

tmp1.SetContentFromBytes stream, "application/octet-stream", ENC_IDENTITY_BINARY

tmp1.EncodeContent ENC_BASE64

End ForAll

End If

 Add a Comment
Subject:
   
Name:
Comment:  (No HTML - Links will be converted if prefixed http://)
 
Remember Me?     Cancel

Search this blog 

Disclaimer 

    About IBM Privacy Contact