Mail format HTML

Mail format HTML

Messagepar Fab2b » 03 Oct 2007 à 12:15

Une petite classe recupérée sur le net utilisant les NOTESMIMEENTITY et autres....Cette classe peut être utilisée pour effectuer des mailings destinés à des boites Lotus et des boites NON lotus. L'interet est que le contenu est du HTML et que les liens et mise en page fonctionnent pour du Lotus et pour du autre chose. On peut donc mettre une photo en entete ou bien ecrire du texte avec du style ou encore faire un lien HREF vers un document.

Code : Tout sélectionner
Public Class SmartMail
   
   Private rcpTo As String
   Private rcpCC As String
   Private rcpBCC As String
   Private s As NotesSession
   Private doc As NotesDocument
   Private body As NotesMIMEEntity
   Private mimeType List As String
   Private isMimeInitialized As Boolean
   Private partCount As Integer
   Private mailbox As NotesDatabase
   
   'Constructeur
   Sub new(theSession As NotesSession)
      Set s=theSession
      If s Is Nothing Then Set s=New NotesSession
      isMimeInitialized=False
      partCount=0
      s.ConvertMIME = False
      Dim thisDb As NotesDatabase
      Set thisDb=s.CurrentDatabase
      Dim thisServer As String
      thisServer=thisDb.Server
      Set mailbox=s.GetDatabase(thisServer,"mail.box")
      If mailbox Is Nothing Then Set mailbox=thisDb
      Set doc=mailbox.CreateDocument()      
      Call doc.ReplaceItemValue("Form", "Memo")
      Set body = doc.CreateMIMEEntity   
   End Sub
   
   'Creer un header
   Sub setHeaderVal(hName As String, hVal As String)
      Dim header As NotesMIMEHeader
      Set header=body.GetNthHeader(hName)
      If header Is Nothing Then Set header=body.CreateHeader(hName)
      Call header.SetHeaderVal(hVal)      
   End Sub
   
   'Set le champ To
   Sub setTo(toStr As String)
      rcpTo=toStr
      Call setHeaderVal("To", toStr)
   End Sub   
   
   'Set le champ CC
   Sub setCC(toStr As String)
      rcpCC=toStr
      Call setHeaderVal("CC", toStr)
   End Sub   
   
   'Set le champ BCC
   Sub setBCC(toStr As String)
      rcpBCC=toStr
      Call setHeaderVal("BCC", toStr)
   End Sub   
   
   'Set le champ Principal
   Sub setPrincipal(toStr As String)
      rcpBCC=toStr
      Call setHeaderVal("Principal", toStr)
   End Sub   
   
   'Set le champ FromTo
   Sub setFromTo(toStr As String)
      rcpBCC=toStr
      Call setHeaderVal("FromTo", toStr)
   End Sub   
   
   'Set le champ Sujet
   Sub setSubject(subject As String)
      Call setHeaderVal("Subject", subject)
   End Sub
   
   'Ajoute un objet fichier dans le corp du mail à partir de son chemin
   Function addFileObject(filepath As String) As String
      addFileObject=""
      Dim theStream As NotesStream
      Set theStream=s.CreateStream()
      If theStream.Open(filepath) Then
         Dim fileSuffix As String
         fileSuffix=Lcase(Strrightback(filepath,"."))
         Dim filename As String
         If Instr(filepath,"/")>0 Then
            filename=Strrightback(filepath,"/")            
         Elseif Instr(filepath,"\")>0 Then
            filename=Strrightback(filepath,"\")            
         Else
            filename=filepath
         End If
         If isKnownMimeType(fileSuffix) Then
            addFileObject=addStreamObject(theStream, mimeType(fileSuffix),{inline; filename="} & filename & {"})
         Else
            Error 9999, {Type of file object "} & filepath & {" is not supported by method SmartMail.addFileObject(). Use SmartMail.addStreamObject() instead.}
         End If
      Else
         Error 53, {File "} & filepath & {" not found in method SmartMail.addFileObject()}
      End If
   End Function
   
   'Ajoute un objet stream dans le corp du mail à partir de son chemin
   Function addStreamObject(theStream As NotesStream, theMimeType As String, disposition As String) As String
      addStreamObject=""
      Call setHeaderVal("Content-Type", "multipart/related")
      Dim part As NotesMimeEntity
      Set part=body.CreateChildEntity()
      Dim idHeader As NotesMimeHeader
      Set idHeader=part.CreateHeader("Content-ID")
      Dim cid As String
      cid=doc.UniversalID+"."+Cstr(partCount)
      Call idHeader.SetHeaderVal("<"+cid+">")
      Dim dispositionHeader As NotesMimeHeader
      Set dispositionHeader=part.CreateHeader("Content-Disposition")
      Call dispositionHeader.SetHeaderValAndParams(disposition)
      Call part.SetContentFromBytes(theStream, theMimeType, ENC_IDENTITY_BINARY)
      partCount=partCount+1
      addStreamObject="cid:"+cid
   End Function
   
   'Insere un contenu HTML dans le body
   Sub setHtmlBody(code As String)
      Dim theStream As NotesStream
      Set theStream=s.CreateStream()
      Call theStream.WriteText(code)
      
      Dim contentTypeHeader As NotesMIMEHeader
      Set contentTypeHeader=body.GetNthHeader("Content-Type")
      Dim textPart As NotesMimeEntity
      If contentTypeHeader Is Nothing Then
         Set textPart=body
      Else
         If Lcase(contentTypeHeader.GetHeaderVal()) Like "multipart/*" Then
            Set textPart=body.CreateChildEntity(body.GetFirstChildEntity())
         Else
            Set textPart=body
         End If
      End If
      Call textPart.SetContentFromText(theStream, "text/html;charset=UTF-8", ENC_NONE)
   End Sub
   
   
   Sub AddTextBody(code As String)
      
      Dim textPart As NotesMimeEntity
      Dim theStream As NotesStream
      Set theStream=s.CreateStream()
      Call theStream.WriteText(code)
      
      Dim contentTypeHeader As NotesMIMEHeader
      Set contentTypeHeader=body.GetNthHeader("Content-Type")
      
      Set textPart=body.CreateChildEntity
      
      Call textPart.SetContentFromText(thestream, "text/html;charset=UTF-8", ENC_NONE)
      
      Call thestream.Truncate
      
   End Sub
   
   
   
   'Envoi
   Sub send()
      Call doc.Send(False)
   End Sub
   
   'Set l'envoyeur et envoi
   Sub setSenderAndSend(sender As String)
      Dim recipients As String
      recipients=rcpTo
      If rcpCC<>"" Then
         If recipients="" Then
            recipients=rcpCC
         Else
            recipients=recipients+","+rcpCC
         End If
      End If
      If rcpBCC<>"" Then
         If recipients="" Then
            recipients=rcpBCC
         Else
            recipients=recipients+","+rcpBCC
         End If         
      End If
      Call doc.ReplaceItemValue("From",sender)
      Call doc.ReplaceItemValue("Recipients",Split(recipients,","))
      Call doc.ReplaceItemValue("PostedDate",Now)
      Call doc.Save(True, False)
   End Sub
   
   'Set le contenu du champ FieldName avec la valeur Fieldvalue
   Sub setMailDocItem(fieldName As String, fieldValue As Variant)
      Call doc.ReplaceItemValue(fieldName, fieldValue)
   End Sub
   
   Function isKnownMimeType(mimeTypeArg As String) As Boolean
      isKnownMimeType=False
      If Not isMimeInitialized Then Call initMimeTypes()
      Forall mt In mimeType
         If Listtag(mt)=mimeTypeArg Then
            isKnownMimeType=True
            Exit Forall
         End If
      End Forall
   End Function
   
   Function getDocument() As NotesDocument
      Set getDocument=doc
   End Function
   
   Private Sub initMimeTypes()
      mimeType("txt")="text/plain"
      mimeType("htm")="text/html"   
      mimeType("html")="text/html"   
      mimeType("css")="text/css"   
      mimeType("js")="text/javascript"   
      mimeType("ics")="text/calendar"
      mimeType("gif")="image/gif"   
      mimeType("jpg")="image/jpeg"   
      mimeType("jpeg")="image/jpeg"   
      mimeType("png")="image/png"
      mimeType("swf")="application/x-shockwave-flash"
      isMimeInitialized=True   
   End Sub
End Class


Public Class SmartKeyValueMap
   Private view As NotesView
   
   Sub new(valueDb As NotesDatabase)
      Dim vdb As NotesDatabase
      Set vdb=valueDb
      If vdb Is Nothing Then
         Dim s As New NotesSession
         Set vdb=s.CurrentDatabase
      End If      
      Set view=vdb.GetView("Key-Value-Pairs")
      If view Is Nothing Then Error 9999, "SmartKeyValueMap object misses the 'Key-Value-Pairs' view. Object will not function and throw errors."
   End Sub
   
   Public Function getValue(key As String) As String
      Dim entry As NotesViewEntry
      Set entry=view.GetEntryByKey(key, True)
      If entry Is Nothing Then
         getValue=""
      Else
         getValue=entry.ColumnValues(1)
      End If
   End Function
   
   Public Function getSmartValue(key As String, default As String)
      getSmartValue=getValue(key)
      If getSmartValue="" Then
         getSmartValue=default
      End If
   End Function   
End Class

Public Class SmartStringTokenizer
   Private m_str As String
   Private m_delim As String
   Private m_pos As Long
   Private m_len As Long
   
   Sub new(theStr As String)
      m_str=theStr
      m_delim=" "
      m_pos=1
      m_len=Len(m_str)+1
   End Sub
   
   Sub setDelimiters(delims As String)
      m_delim=delims
   End Sub
   
   Function hasMoreTokens() As Boolean
'      If Instr(1,m_str,m_delim)>0 Then
      If Mid(m_str, m_pos) Like "*[!" & m_delim & "]*" Then      
         hasMoreTokens=True
      Else
         hasMoreTokens=False
      End If
   End Function
   
   Function nextToken() As String
      If Not hasMoreTokens() Then Error 9980, "No such element."
      
      Dim beginPos As Long
      Dim endPos As Long
      beginPos=0
      endPos=0
      
      Dim char As String      
      While (endPos=0) And (m_pos<m_len)
         char=Mid(m_str,m_pos,1)
         If Instr(m_delim,char)>0 Then
            If Not (beginPos=0) Then endPos=m_pos
         Else
            If beginPos=0 Then beginPos=m_pos
         End If
         m_pos=m_pos+1
      Wend
      If endPos=0 Then endPos=m_pos
      nextToken=Mid(m_str,beginPos,endPos-beginPos)
   End Function
End Class



Utilisation de la classe dans un agent (Use "La class" dans les déclarations) :

Code : Tout sélectionner
'On fabrique le mail a envoyer en utilisant la classe MIME
Dim DocMail As New SmartMail(session)

Call DocMail.setPrincipal(Expediteur)
   
'Le sujet
Call DocMail.setSubject("Ici on saisi le sujet du mail")
   
'La photo de l'entete
Call DocMail.addFileObject(RepertoireTravail+"\RepFichier\"+NomFichier)   
   
'Le corps
Call docmail.addTextBody({<Font size="2" face="Arial"><BR><BR>Hello,</font>} )
   
Call docmail.addTextBody({<Font size="2" face="Arial"><BR><BR><BR></font>} )

Call docmail.addTextBody({<Font size="2" face="Arial" color=red>The following requests for "Can you help me...? - } +Rubrique+{" have been made this week:<BR><BR><BR></font>} )

'Ajout d'un HREF vers un document de la base.
Chaine = Chaine + {<Font size="2" face="Arial" color=red><A HREF="http://}+nomserver+{/__} + IDAccueil+_
         {.nsf/WEBLIEN?Readform&IDB=}+DocREs.IDBASEORI(0) +{&ID=}+DocRes.IDFDOCORI(0)+{&">} + DocRes.TIT(0) +{</A></Font> }         
Call docmail.addTextBody(chaine)

Call DocMail.setto(NomUser)

Call DocMail.Send()

   
Fab2b
Premier posts
Premier posts
 
Message(s) : 31
Inscrit(e) le : 04 Sep 2007 à 16:06

Messagepar oguruma » 03 Oct 2007 à 12:25

:( si j'avais vu cette classe il y a un an, j'aurai eu je crois moins de galères - merci super -
Bien à vous

http://www.dominoarea.org/oguruma/

Les téléphones PORTABLES dans les TGV y en a MARRRE de ces voyageurs qui ne respectent pas les autres ! ARRET DES PORTABLES SVP - Merci

Fumeurs ! respectez les non fumeurs !!!
Fumeurs ! respectez la loi de février 2007 et les lieux publics !!! (ie. hall de gares)
Avatar de l’utilisateur
oguruma
Super V.I.P.
Super V.I.P.
 
Message(s) : 4086
Inscrit(e) le : 16 Déc 2004 à 08:50
Localisation : LILLE

Insertion de MIME dans un document Notes

Messagepar stloje » 18 Mars 2010 à 10:38

Voici une autre façon d'inclure du MIME dans un document Notes pour y insérer du HTML.

Cette classe ne tient pas compte de l'envoi par courriel (donc pas de saisie de destinataire, sujet et autres éléments d'un courriel). Le sujet est déjà traité dans la réponse précédente par Fab2b.

ATTENTION : le MIME doit se mettra automatique dans le champ "Body". Notes indique que seul ce champ a été spécialement conçu pour recevoir du MIME

Fripouille76 a écrit:juste pour information, tous les champs text rich fonctionne pas seulement le Body, suffis juste de cocher l'option "Mime/Html" dans le deuxieme onglet du champ.


Code à mettre dans la partie Declaration
Code : Tout sélectionner
%REM
Cette classe contient les fonctions pouvant être exécutées en MIME
body : entité MIME
header : entête de l'entité MIME
stream : flux de données

InsertHeader : crée l'entête de la partie MIME
   entrée :
      headerType : le nom de l'entête à insérer
      headerValue : la valeur de l'entête
SearchHeaderValue : recherche la valeur d'un entête
   entrée : headerType : le nom de l'entête à rechercher
   sortie : la valeur de l'entête trouvée, sinon vide
InsertStream : insère le texte dans le corps du message
   entrée : textLine : chaîne de caractères
TruncateStream : efface le tampon créé par Stream
LinkStream : fonction qui force l'écrire de la mémoire tampon dans le corps de l'entité
CleanText : retire les caractères accentués et les transforme en caractère ascii ou ISO
   entrée : caract : chaîne de caractères à traiter
            forceISOCarac : vrai si doit être transformé en ISO, sinon faux
   sortie : la chaîne de caract transformée
FileAttachement : rattache un fichier au contenu MIME
   entrée : fileName : le nom du fichier à rattacher
%END REM
Public Class MIMEActions
   Private body As NotesMIMEEntity
   Private header As NotesMIMEHeader
   Private stream As NotesStream
   Private session As NotesSession
   
   Sub new (doc As NotesDocument)
      Set session = New NotesSession
      'on empêche temporairement la conversion du texte
      session.ConvertMIME = False
      Set body = doc.CreateMIMEEntity
      Set stream = session.CreateStream
   End Sub
   
   Public Function insertHeader (Byval headerType As String, Byval headerValue As String) As Boolean
%REM
type de header connus
- Content-Type
%END REM
      
      insertHeader = False
      'on vérifie si l'entête existe
      If searchHeaderValue (headerType) <> "" Then
         'on crée l'entête
         Set header = body.createHeader (headerType)
         Call header.setHeaderVal (headerValue)
         insertHeader = True
      End If
   End Function
   
   Private Property Get searchHeaderValue (headerType As String) As String
      If Not body.getNthHeader (headerType) Is Nothing Then
         searchHeaderValue = body.getNthHeader (headerType).getHeaderVal ()
      End If
   End Property
   
   Public Sub insertStream (textLine As String)
      Call stream.WriteText(textLine)   
   End Sub
   
   Public Sub truncateStream ()
      Call stream.Truncate
   End Sub
   
   Public Property Get hasStreamValue As Long
      hasStreamValue = stream.Bytes
   End Property
   
   Public Sub linkStream ()
      'on insère le contenu du texte avant de supprimer la chaîne
      Call body.setContentFromText(stream, "text/HTML;charset=ISO-8859-1", ENC_QUOTED_PRINTABLE)
      Call truncateStream ()
   End Sub
   
   Public Function cleanText (Byval caract As String, Byval forceISOCaract As Boolean) As String
      Dim tmp As String
      Dim i As Integer
      Dim debut As Boolean
      Dim ISOCarac As Boolean
      
      debut = False
      For i = 1 To Len(caract)
         tmp = Mid$ (caract, i, 1)
         'on s'assure que les caractères ne font pas partis d'une balise HTML
         If tmp = ">" Then debut = False
         If tmp = "<" Then debut = True
         
         'est-on dans une balise?
         If debut = False Then
            'on vérifie si on doit forcer la transformation en ISO
            If forceISOCaract = True Then
               'est-ce qu'il y a déjà eu l'entête de ISO?
               If ISOCarac = False Then
                  cleanText = CleanText & "=?ISO-8859-1?Q?"
                  ISOCarac = True
               End If
            End If
            If Instr(|azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890 <>;,:?./%=|, tmp) = 0 Then
               cleanText = cleanText & "&#x" & Hex$ (Uni (tmp)) & ";"
            Else
               cleanText = cleanText & tmp
            End If 
         End If
      Next
      'on termine le bloc concernant ISO
      If forceISOCaract = True Then cleanText = cleanText + "?="      
   End Function
   
   Public Sub fileAttachement (Byval fileName As String)
      Dim strContentType As String
      
      'set correct content types for known file types
      Select Case Lcase (Strright (fileName, "."))
      Case "gif"
         strContentType = "image/gif"
      Case "jpeg", "jpg"
         strContentType = "image/jpeg"
      Case Else
         strContentType = "application/octet-stream"
      End Select
      
      'on crée directement le type d'entête pour éviter de l'oublier
      Call Me.insertHeader ("Content-Disposition", {attachment; filename="} & fileName & {"})
      If stream.Open(fileName) Then
         Call body.setContentFromBytes(stream, strContentType & {; name="} & fileName & {"}, ENC_IDENTITY_BINARY)
         Call stream.Close
      End If
      
   End Sub
   
End Class


Voici un exemple de code pour créer un élément en MIME
Code : Tout sélectionner
   Dim session As New NotesSession
   Dim doc As New NotesDocument (session.CurrentDatabase)
   
   
   Dim MIMEDoc As MIMEActions
   
   doc.form = "Info"
   doc.Title = "test MIME"
   
   'on initialise la partie MIME sur le document
   Set MIMEDoc = New MIMEActions (doc)
   'on insère le type d'entête
   Call MIMEDoc.insertHeader ("content-type", "text/html")
   
   'maintenant, on insère le code HTML
   Call MIMEDoc.insertStream ("<Table>")
   Call MIMEDoc.insertStream ("<TR>")
   Call MIMEDoc.insertStream ("<TD>Ceci est</TD>")
   Call MIMEDoc.insertStream ("<TD>un example</TD>")
   Call MIMEDoc.insertStream ("<TD>de tableau</TD>")
   Call MIMEDoc.insertStream ("</TR>")
   Call MIMEDoc.insertStream ("<TR>")
   Call MIMEDoc.insertStream ("<TD><center>Fait via MIME</center></TD>")   
   Call MIMEDoc.insertStream ("</TR>")
   Call MIMEDoc.insertStream ("</Table>")
   
   'on force le code HTML dans le document
   Call MIMEDoc.linkStream
   Call doc.Save (True, False)
Et vive le cambouis! Si t'en as jusque sous les bras, c'est parce que tu as cherché longuement la solution ou tout simplement parce que tu t'es vautré!
Avatar de l’utilisateur
stloje
Posteur expérimenté
Posteur expérimenté
 
Message(s) : 335
Inscrit(e) le : 09 Sep 2008 à 13:18
Localisation : Orléans

Messagepar Thelonious » 11 Mai 2011 à 14:08

Bonjour,

Cette classe marche très bien et est très utile !
Juste une petite question : comment fait-on pour intégrer le résultat d'un champ notes dans une des cellules du tableau ?

J'ai essayé d'envoyer un mail HTML depuis un masque Notes qui contient
différents champs mais je n'y arrive pas ...
Si quelqu'un a une idée ...

Merci d'avance !
Avatar de l’utilisateur
Thelonious
Apprenti-posteur
Apprenti-posteur
 
Message(s) : 106
Inscrit(e) le : 16 Déc 2004 à 11:58
Localisation : Région Parisienne

Messagepar Thelonious » 11 Mai 2011 à 17:59

A priori, lorsque je mets ce type de code, ça fonctionne :

Code : Tout sélectionner
<TR>
      <TD>Operation</TD>
      <TD>}+doc.MonChamp(0)+{</TD>
    </TR>
Avatar de l’utilisateur
Thelonious
Apprenti-posteur
Apprenti-posteur
 
Message(s) : 106
Inscrit(e) le : 16 Déc 2004 à 11:58
Localisation : Région Parisienne


Retour vers Messagerie (mail... etc...)