Envoyer des messages avec fichiers
Ce guide explique comment envoyer des fichiers joints de maniere securisee.
Deux methodes pour joindre des fichiers
- Par chemin de fichier (
FilesPath) - Fichiers sur le disque - Par contenu binaire (
FileArgs) - Fichiers en memoire
Methode 1 : Fichiers par chemin
Exemple rapide
var args = new MutliRecipientArgs(
endpoint, serial, apiUser, apiPassword,
recipients, message, subject,
null, null, SendMethodEnum.onlyEmail,
false, true, true, "fr-CA", 5, 1440
);
// Ajouter des fichiers par leur chemin
args.FilesPath = new List<string>
{
@"C:\Documents\rapport.pdf",
@"C:\Documents\facture.xlsx"
};
var response = MessageHelper.MultiRecipientMessage(args);
Exemple complet : Envoi de documents contractuels
using System;
using System.Collections.Generic;
using System.IO;
using SecureExchangesSDK.Helpers;
using SecureExchangesSDK.Models.Args;
using SecureExchangesSDK.Models.Entity;
using SecureExchangesSDK.SecureExchanges;
public class ContractDeliveryService
{
private readonly Guid _serial;
private readonly Guid _apiUser;
private readonly Guid _apiPassword;
public ContractDeliveryService(Guid serial, Guid apiUser, Guid apiPassword)
{
_serial = serial;
_apiUser = apiUser;
_apiPassword = apiPassword;
}
/// <summary>
/// Envoie un contrat avec ses annexes
/// </summary>
public SendResult SendContract(
string recipientEmail,
string recipientName,
string contractPath,
List<string> annexPaths = null)
{
// Validation des fichiers
if (!File.Exists(contractPath))
return new SendResult { Success = false, Error = "Contrat introuvable" };
// Preparer la liste des fichiers
var filePaths = new List<string> { contractPath };
if (annexPaths != null)
{
foreach (var path in annexPaths)
{
if (File.Exists(path))
filePaths.Add(path);
}
}
// Calculer la taille totale
long totalSize = 0;
foreach (var path in filePaths)
{
totalSize += new FileInfo(path).Length;
}
// Verification de la limite (2.5 Go)
if (totalSize > 2.5 * 1024 * 1024 * 1024)
return new SendResult { Success = false, Error = "Taille totale depasse 2.5 Go" };
// Creer le message HTML
string htmlBody = $@"
<h2>Bonjour {recipientName},</h2>
<p>Veuillez trouver ci-joint votre contrat ainsi que les documents annexes.</p>
<p><strong>Documents joints :</strong></p>
<ul>
<li>{Path.GetFileName(contractPath)} (Contrat principal)</li>
{string.Join("", annexPaths?.Select(p => $"<li>{Path.GetFileName(p)}</li>") ?? Array.Empty<string>())}
</ul>
<p>Merci de nous retourner le contrat signe dans les meilleurs delais.</p>";
// Configuration des arguments
var recipients = new List<RecipientInfo>
{
new RecipientInfo { Email = recipientEmail }
};
Uri endpoint = new Uri("https://www.secure-exchanges.com/_api/0217/0217.asmx");
var args = new MutliRecipientArgs(
endpoint,
_serial,
_apiUser,
_apiPassword,
recipients,
htmlBody,
"Votre contrat - Documents a signer",
password: null,
filesList: null,
SendMethodEnum.onlyEmail,
sendByMyOwnSMTPServer: false,
showSubject: true,
getNotify: true,
culture: "fr-CA",
maxOpeningTime: 10,
expirationMinutes: 10080 // 7 jours
);
// Attacher les fichiers par chemin
args.FilesPath = filePaths;
// Envoyer
var response = MessageHelper.MultiRecipientMessage(args);
if (response.Status == 200)
{
return new SendResult
{
Success = true,
MessageUrl = response.RecipientsAnswer[0].Answer.URL,
FileCount = filePaths.Count,
TotalSize = totalSize
};
}
return new SendResult
{
Success = false,
Error = response.Data
};
}
}
public class SendResult
{
public bool Success { get; set; }
public string MessageUrl { get; set; }
public string Error { get; set; }
public int FileCount { get; set; }
public long TotalSize { get; set; }
}
Methode 2 : Fichiers en memoire (FileArgs)
Utilisez cette methode quand :
- Les fichiers sont generes dynamiquement
- Vous travaillez avec des flux de donnees
- Les fichiers ne sont pas sur le disque
Exemple rapide
// Creer un FileArgs a partir de donnees en memoire
var pdfBytes = File.ReadAllBytes(@"C:\temp\document.pdf");
var fileArgs = new FileArgs(pdfBytes, "document.pdf", "application/pdf");
var args = new MutliRecipientArgs(
endpoint, serial, apiUser, apiPassword,
recipients, message, subject,
password: null,
filesList: new List<FileArgs> { fileArgs },
SendMethodEnum.onlyEmail,
false, true, true, "fr-CA", 5, 1440
);
Exemple complet : Generation de rapport PDF
using System;
using System.Collections.Generic;
using System.IO;
using SecureExchangesSDK.Helpers;
using SecureExchangesSDK.Models.Args;
using SecureExchangesSDK.Models.Entity;
using SecureExchangesSDK.SecureExchanges;
public class ReportDeliveryService
{
private readonly Guid _serial;
private readonly Guid _apiUser;
private readonly Guid _apiPassword;
public ReportDeliveryService(Guid serial, Guid apiUser, Guid apiPassword)
{
_serial = serial;
_apiUser = apiUser;
_apiPassword = apiPassword;
}
/// <summary>
/// Genere et envoie un rapport mensuel
/// </summary>
public SendResult SendMonthlyReport(
string recipientEmail,
string companyName,
byte[] reportPdfBytes,
byte[] dataExcelBytes = null)
{
// Preparer les fichiers en memoire
var files = new List<FileArgs>
{
new FileArgs(
reportPdfBytes,
$"Rapport_{companyName}_{DateTime.Now:yyyy-MM}.pdf",
"application/pdf"
)
};
// Ajouter le fichier Excel si present
if (dataExcelBytes != null && dataExcelBytes.Length > 0)
{
files.Add(new FileArgs(
dataExcelBytes,
$"Donnees_{companyName}_{DateTime.Now:yyyy-MM}.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
));
}
// Message HTML
string htmlBody = $@"
<h2>Rapport mensuel - {companyName}</h2>
<p>Veuillez trouver ci-joint votre rapport mensuel pour {DateTime.Now:MMMM yyyy}.</p>
<p>Ce rapport contient :</p>
<ul>
<li>Synthese des activites</li>
<li>Indicateurs de performance</li>
{(dataExcelBytes != null ? "<li>Donnees detaillees (Excel)</li>" : "")}
</ul>
<p>N'hesitez pas a nous contacter pour toute question.</p>";
// Configuration
var recipients = new List<RecipientInfo>
{
new RecipientInfo { Email = recipientEmail }
};
Uri endpoint = new Uri("https://www.secure-exchanges.com/_api/0217/0217.asmx");
var args = new MutliRecipientArgs(
endpoint,
_serial,
_apiUser,
_apiPassword,
recipients,
htmlBody,
$"Rapport mensuel {DateTime.Now:MMMM yyyy} - {companyName}",
password: null,
filesList: files, // Fichiers en memoire
SendMethodEnum.onlyEmail,
sendByMyOwnSMTPServer: false,
showSubject: true,
getNotify: true,
culture: "fr-CA",
maxOpeningTime: 5,
expirationMinutes: 20160 // 14 jours
);
var response = MessageHelper.MultiRecipientMessage(args);
return new SendResult
{
Success = response.Status == 200,
MessageUrl = response.Status == 200 ? response.RecipientsAnswer[0].Answer.URL : null,
Error = response.Status != 200 ? response.Data : null
};
}
}
Types MIME courants
| Extension | Type MIME |
|---|---|
.pdf |
application/pdf |
.doc |
application/msword |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls |
application/vnd.ms-excel |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.png |
image/png |
.jpg |
image/jpeg |
.zip |
application/zip |
.txt |
text/plain |
Limites et recommandations
| Limite | Valeur |
|---|---|
| Taille maximale totale | 2.5 Go |
| Nombre de fichiers | Illimite (dans la limite de taille) |
| Types de fichiers | Tous types acceptes |
Tip
Pour les fichiers volumineux, utilisez FilesPath plutot que FileArgs pour eviter de charger tout le fichier en memoire.