Option Explicit
Private CdoConfig As Object
Private CdoConfigErrorMessage As String
Function GetCdoConfig() As Boolean
On Error GoTo FIN_CDO_Config
If CdoConfig Is Nothing Then
Set CdoConfig = CreateObject("CDO.Configuration")
CdoConfig.Load -1
With CdoConfig.Fields
' --- configuration des variables CDO pour gmail
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com" ' Adapter
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
' --- authentification ---
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = "1"
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "adresse@gmail.com" ' Adapter
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "motdepasse" ' Adapter
' --- connexion ssl ---
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = "true"
.Update
End With
End If
' --- Sortie et gestion des erreurs ---
FIN_CDO_Config:
If Err.Number <> 0 Then CdoConfigErrorMessage = Err.Description
On Error GoTo 0
End Function
Sub EnvoiMail(Objet As String, Destinataires As String, Optional Cachés As String = "")
Dim cdo_msg As Object
Dim cellule As Range, plage As Range
Dim Ligne As Long
'Set plage = ThisWorkbook.Sheets("Messages").Range("A1:A1000")
'
' L'appel à la fonction GetCdoConfig
' Vérifiera si la configuration existe déjà
'
If GetCdoConfig() Then
'
'Commencer la boucle de création et d'envoi de message individuel
For Each cellule In plage
Set cdo_msg = CreateObject("CDO.Message")
With cdo_msg
Set .Configuration = CdoConfig
.MimeFormatted = True
.GetStream.Charset = "utf-8"
.BodyPart.Charset = "utf-8"
.BodyPart.ContentTransferEncoding = "base64"
.To = Destinataires
If Cachés <> "" Then .BCC = Cachés
.From = "coco@lariflette.fr"
.Subject = Objet ' A construire
If TextBody <> "" Then .TextBody = TextBody ' A définir et construire
If HtmlBody <> "" Then .HtmlBody = HtmlBody ' A définir et construire
If PieceJointe <> "" Then
If Dir(Trim(PieceJointe)) <> "" Then
.AddAttachment Trim(PieceJointe) ' A définir
Else
If MsgBox("Pièce jointe introuvable : " & vbCrLf & PieceJointe & vbCrLf & vbCrLf _
& "Envoyer quand même le message ?", vbQuestion + vbYesNo, "Envoyer un message") = vbNo Then
GoTo FIN
End If
End If
End If
.Send
End With
Set cdo_msg = Nothing
Next
'
' Destruction de l'objet configuration si il n'a plus lieu d'être
' Set CdoConfig = Nothing
Else
'
' Eventuellement afficher le message
' d'erreur de configuration
MsgBox "Envoi mail interrompu en raison de l'erreur suivante : " & vbCrLf & vbCrLf & _
CdoConfigErrorMessage, vbExclamation, "Relance personnalisée"
End If
FIN:
End Sub