Files
tsGmail/GmailOAuthSender.cs
2025-09-18 13:00:36 +02:00

208 lines
8.7 KiB
C#

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
public static class GmailOAuthSender
{
public static async Task EnviarCorreoAsync(GmailConfig config,
string tokenOAuth,
string destinatarios,
string asunto,
string cuerpo,
bool cuerpoHtml = false,
string cc = "",
string bcc = "",
string responderA = "",
List<Attachment> adjuntos = null,
string servidorSMTP = "smtp.gmail.com",
int puerto = 587)
{
if (tokenOAuth=="") tokenOAuth = await GmailTokenManager.ObtenerAccessTokenAsync(config);
var mensaje = new MimeMessage();
mensaje.From.Add(new MailboxAddress(config.NombreRemitente ?? config.Remitente, config.Remitente));
foreach (var d in destinatarios.Split(';').Where(x => !string.IsNullOrWhiteSpace(x)))
mensaje.To.Add(new MailboxAddress(d.Trim(), d.Trim()));
if (!string.IsNullOrWhiteSpace(cc))
foreach (var c in cc.Split(';'))
mensaje.Cc.Add(new MailboxAddress(c.Trim(), c.Trim()));
if (!string.IsNullOrWhiteSpace(bcc))
foreach (var b in bcc.Split(';'))
mensaje.Bcc.Add(new MailboxAddress(b.Trim(), b.Trim()));
mensaje.ReplyTo.Add(new MailboxAddress(string.IsNullOrWhiteSpace(responderA) ? config.NombreRemitente : responderA,
string.IsNullOrWhiteSpace(responderA) ? config.Remitente : responderA));
mensaje.Subject = asunto.Replace("\r", "").Replace("\n", " ");
var builder = new BodyBuilder
{
HtmlBody = cuerpoHtml ? cuerpo : null,
TextBody = cuerpoHtml ? null : cuerpo
};
if (adjuntos != null)
{
foreach (var att in adjuntos)
{
var ms = new MemoryStream();
att.ContentStream.CopyTo(ms);
builder.Attachments.Add(att.Name, ms.ToArray());
}
}
mensaje.Body = builder.ToMessageBody();
var cliente = new MailKit.Net.Smtp.SmtpClient();
cliente.ServerCertificateValidationCallback = (s, c, ch, e) => true;
await cliente.ConnectAsync(servidorSMTP, puerto, SecureSocketOptions.StartTls);
await cliente.AuthenticateAsync(new SaslMechanismOAuth2(config.Remitente, tokenOAuth));
await cliente.SendAsync(mensaje);
await cliente.DisconnectAsync(true);
}
public static async Task EnviarCorreoALAsync(GmailConfig config,
string tokenOAuth,
string destinatarios,
string asunto,
string cuerpo,
bool cuerpoHtml = false,
string cc = "",
string bcc = "",
string responderA = "",
ArrayList adjuntos = null,
string servidorSMTP = "smtp.gmail.com",
int puerto = 587)
{
if (string.IsNullOrEmpty(tokenOAuth))
tokenOAuth = await GmailTokenManager.ObtenerAccessTokenAsync(config);
var mensaje = new MimeMessage();
mensaje.From.Add(new MailboxAddress(config.NombreRemitente ?? config.Remitente, config.Remitente));
foreach (var d in destinatarios.Split(';').Where(x => !string.IsNullOrWhiteSpace(x)))
mensaje.To.Add(new MailboxAddress(d.Trim(), d.Trim()));
if (!string.IsNullOrWhiteSpace(cc))
foreach (var c in cc.Split(';'))
mensaje.Cc.Add(new MailboxAddress(c.Trim(), c.Trim()));
if (!string.IsNullOrWhiteSpace(bcc))
foreach (var b in bcc.Split(';'))
mensaje.Bcc.Add(new MailboxAddress(b.Trim(), b.Trim()));
mensaje.ReplyTo.Add(new MailboxAddress(
string.IsNullOrWhiteSpace(responderA) ? config.NombreRemitente : responderA,
string.IsNullOrWhiteSpace(responderA) ? config.Remitente : responderA));
mensaje.Subject = asunto.Replace("\r", "").Replace("\n", " ");
var builder = new BodyBuilder
{
HtmlBody = cuerpoHtml ? cuerpo : null,
TextBody = cuerpoHtml ? null : cuerpo
};
if (adjuntos != null)
{
foreach (var item in adjuntos)
{
if (item is Attachment att)
{
var ms = new MemoryStream();
att.ContentStream.CopyTo(ms);
builder.Attachments.Add(att.Name, ms.ToArray());
}
else
{
throw new InvalidCastException("El objeto en adjuntos no es de tipo Attachment.");
}
}
}
mensaje.Body = builder.ToMessageBody();
var cliente = new MailKit.Net.Smtp.SmtpClient();
cliente.ServerCertificateValidationCallback = (s, c, ch, e) => true;
await cliente.ConnectAsync(servidorSMTP, puerto, SecureSocketOptions.StartTls);
await cliente.AuthenticateAsync(new SaslMechanismOAuth2(config.Remitente, tokenOAuth));
await cliente.SendAsync(mensaje);
await cliente.DisconnectAsync(true);
}
public static async Task EnviarCorreoMSAsync(GmailConfig config,
string tokenOAuth,
string destinatarios,
string asunto,
string cuerpo,
bool cuerpoHtml = false,
string cc = "",
string bcc = "",
string responderA = "",
MemoryStream[] FicherosAdjuntos = null,
String[] NombreFicherosAdjuntos = null,
string servidorSMTP = "smtp.gmail.com",
int puerto = 587)
{
if (string.IsNullOrEmpty(tokenOAuth))
tokenOAuth = await GmailTokenManager.ObtenerAccessTokenAsync(config);
var mensaje = new MimeMessage();
mensaje.From.Add(new MailboxAddress(config.NombreRemitente ?? config.Remitente, config.Remitente));
foreach (var d in destinatarios.Split(';').Where(x => !string.IsNullOrWhiteSpace(x)))
mensaje.To.Add(new MailboxAddress(d.Trim(), d.Trim()));
if (!string.IsNullOrWhiteSpace(cc))
foreach (var c in cc.Split(';'))
mensaje.Cc.Add(new MailboxAddress(c.Trim(), c.Trim()));
if (!string.IsNullOrWhiteSpace(bcc))
foreach (var b in bcc.Split(';'))
mensaje.Bcc.Add(new MailboxAddress(b.Trim(), b.Trim()));
mensaje.ReplyTo.Add(new MailboxAddress(
string.IsNullOrWhiteSpace(responderA) ? config.NombreRemitente : responderA,
string.IsNullOrWhiteSpace(responderA) ? config.Remitente : responderA));
mensaje.Subject = asunto.Replace("\r", "").Replace("\n", " ");
var builder = new BodyBuilder
{
HtmlBody = cuerpoHtml ? cuerpo : null,
TextBody = cuerpoHtml ? null : cuerpo
};
if (FicherosAdjuntos != null)
{
for (int i = 0; i < NombreFicherosAdjuntos.Length; i++)
{
builder.Attachments.Add(NombreFicherosAdjuntos[i], FicherosAdjuntos[i].ToArray());
}
}
mensaje.Body = builder.ToMessageBody();
var cliente = new MailKit.Net.Smtp.SmtpClient();
cliente.ServerCertificateValidationCallback = (s, c, ch, e) => true;
await cliente.ConnectAsync(servidorSMTP, puerto, SecureSocketOptions.StartTls);
await cliente.AuthenticateAsync(new SaslMechanismOAuth2(config.Remitente, tokenOAuth));
await cliente.SendAsync(mensaje);
await cliente.DisconnectAsync(true);
}
}