private void SendMessageClick(object sender, RoutedEventArgs e) { MailBuilder builder = new MailBuilder(); builder.From.Add(new MailBox(from_textBox.Text, "Hello")); builder.To.Add(new MailBox(to_textBox.Text, "World")); builder.Subject = subject_textBox.Text; builder.Text = messageText_textBox.Text; IMail email = builder.Create(); // отправка сообщения using (Smtp smtp = new Smtp()) { smtp.ConnectSSL("smtp.gmail.com"); smtp.UseBestLogin("email", "password"); //вставляем email и пароль ISendMessageResult result = smtp.SendMessage(email); if (result.Status == SendMessageStatus.Success) { MessageBox.Show("Сообщение отправленно!"); } smtp.Close(); } }
static void Main() { IMail email = Mail .Html(@"<img src=""cid:lemon@id"" align=""left"" /> This is simple <strong>HTML email</strong> with an image and attachment") .Subject("Subject") .AddVisual("Lemon.jpg").SetContentId("lemon@id") .AddAttachment("Attachment.txt").SetFileName("Invoice.txt") .From(new MailBox("*****@*****.**", "Lemon Ltd")) .To(new MailBox("*****@*****.**", "John Smith")) .Create(); email.Save(@"SampleEmail.eml"); // You can save the email for preview. using (Smtp smtp = new Smtp()) // Now connect to SMTP server and send it { smtp.Connect(_server); // Use overloads or ConnectSSL if you need to specify different port or SSL. smtp.UseBestLogin(_user, _password); // You can also use: Login, LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods, // or use UseBestLogin method if you want Mail.dll to choose for you. ISendMessageResult result = smtp.SendMessage(email); Console.WriteLine(result.Status); smtp.Close(); } // For sure you'll need to send complex emails, // take a look at our templates support in SmtpTemplates sample. }
static void Main() { // Create test data for the template: Order order = new Order(); order.OrderId = 7; order.CustomerName = "John Smith"; order.Currency = "USD"; order.Items.Add(new OrderItem { Name = "Yellow Lemons", Quantity = "22 lbs", Price = 149 }); order.Items.Add(new OrderItem { Name = "Green Lemons", Quantity = "23 lbs", Price = 159 }); // Load and render the template with test data: string html = Template .FromFile("Order.template") .DataFrom(order) .PermanentDataFrom(DateTime.Now) // Year is used in the email footer/ .Render(); // You can save the HTML for preview: File.WriteAllText("Order.html", html); // Create an email: IMail email = Mail.Html(Template .FromFile("Order.template") .DataFrom(order) .PermanentDataFrom(DateTime.Now) .Render()) .Text("This is text version of the message.") .AddVisual("Lemon.jpg").SetContentId("lemon@id") // Here we attach an image and assign the content-id. .AddAttachment("Attachment.txt").SetFileName("Invoice.txt") .From(new MailBox("*****@*****.**", "Lemon Ltd")) .To(new MailBox("*****@*****.**", "John Smith")) .Subject("Your order") .Create(); // Send this email: using (Smtp smtp = new Smtp()) // Connect to SMTP server { smtp.Connect(_server); // Use overloads or ConnectSSL if you need to specify different port or SSL. smtp.UseBestLogin(_user, _password); // You can also use: Login, LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods, // or use UseBestLogin method if you want Mail.dll to choose for you. ISendMessageResult result = smtp.SendMessage(email); Console.WriteLine(result.Status); smtp.Close(); } }
static void Main() { ISendMessageResult result = Mail.Html(@"<img src=""cid:lemon@id"" align=""left"" /> This is simple <strong>HTML email</strong> with an image and attachment") .Subject("Subject") .AddVisual("Lemon.jpg").SetContentId("lemon@id") .AddAttachment("Attachment.txt").SetFileName("document.txt") .From("*****@*****.**") .To("*****@*****.**") .UsingNewSmtp() .Server(_server) .WithSSL() .WithCredentials(_user, _password) .Send(); Console.WriteLine(result.Status); // For sure you'll need to send complex emails, // take a look at our templates support in SmtpTemplates sample. }
/// <summary> Spedisce l'email. </summary> /// <param name="mailbox"> MailBox da dove spedire l'email. </param> /// <param name="email"> Email da spedire. </param> /// <param name="pecMail"> PEC da inviare </param> /// <param name="guid"> Guid della mail</param> public bool SendMail(PECMailBox mailbox, IMail email, PECMail pecMail, Guid guid, string password) { // In caso di modalità DEBUG modifico i destinatari con quello di default: if (_parameters.DebugModeEnabled) { // Creo una nuova mail alla quale aggiungo come allegato la mail originale MailBuilder debugBuilder = new MailBuilder(); debugBuilder.From.Add(email.From.First()); debugBuilder.Subject = string.Format("Inoltro messaggio per DEBUG -> {0}", email.Subject); // Crea il corpo del messaggio di default (non è richiesto dall'Interoperabilità) o lo legge da base dati, se indicato debugBuilder.Text = "In allegato la mail che sarebbe stata spedita."; // Aggiungo il destinatario di debug debugBuilder.To.Add(new MailBox(_parameters.PecOutAddressDebugMode, "DEBUG ADDRESS")); // Aggiungo la mail come allegatos debugBuilder.AddAttachment(email); // Sostituisco item con il debugMail email = debugBuilder.Create(); FileLogger.Info(_loggerName, string.Format("Modificato l'indirizzo di invio della PEC con l'indirizzo {0}.", _parameters.PecOutAddressDebugMode)); } // Eseguo in modo atomico il blocco di invio int i = 0; bool sent = false; ISendMessageResult sendResult = null; Exception lastException = null; while (!sent && i < 5) { try { using (Smtp smtp = new Smtp()) { smtp.ServerCertificateValidate += ServerCertificateValidateHandler; // Utilizzo connessione SSL if (mailbox.OutgoingServerUseSsl.HasValue && mailbox.OutgoingServerUseSsl.Value) { smtp.SSLConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12; smtp.ConnectSSL(mailbox.OutgoingServerName, mailbox.OutgoingServerPort.HasValue ? mailbox.OutgoingServerPort.Value : 465); } else { smtp.Connect(mailbox.OutgoingServerName, mailbox.OutgoingServerPort.HasValue ? mailbox.OutgoingServerPort.Value : 25); } // Utilizzo autenticazione if (!string.IsNullOrEmpty(mailbox.Username) && !string.IsNullOrEmpty(password)) { smtp.UseBestLogin(mailbox.Username, password); } sendResult = smtp.SendMessage(email); sent = (sendResult.Status == SendMessageStatus.Success); if (!sent) { string errors = string.Empty; if (sendResult.GeneralErrors != null && sendResult.GeneralErrors.Any()) { errors = string.Join(", ", sendResult.GeneralErrors .Select(f => string.Concat("Code: ", f.Code, " - EnhancedStatusCode: ", f.EnhancedStatusCode, " - Message: ", f.Message, " - Status : ", f.Status))); } FileLogger.Error(_loggerName, string.Format("Errore in spedizione PEC {0} / casella {1} - {2}. Stato spedizione: {3} - Errori:{4}.", pecMail.Id, mailbox.Id, mailbox.MailBoxName, sendResult.Status, errors)); } smtp.Close(false); } if (!sent) { continue; } // Aggiorno immediatamente la PEC come spedita in modo da non avere dubbi che la PEC sia stata davvero spedita pecMail.MailDate = DateTime.Now; pecMail.XRiferimentoMessageID = string.Format("<{0}>", guid); _factory.PECMailFacade.UpdateOnly(ref pecMail); Protocol currentProtocol = _factory.PECMailFacade.GetProtocol(pecMail); if (currentProtocol != null && (short)ProtocolKind.FatturePA == currentProtocol.IdProtocolKind) { currentProtocol.IdStatus = (int)ProtocolStatusId.PAInvoiceSent; _factory.ProtocolFacade.UpdateOnly(ref currentProtocol); } } catch (Exception ex) { lastException = ex; // Se mi trovo in questo status è avvenuto un errore in fase di spedizione, per cui posso riprocedere ad inviare FileLogger.Error(_loggerName, string.Format("Non è stato possibile inviare la PEC {0} / casella {1} - {2} per un probabile errore di rete o di server PEC. La procedura verrà ritentata. - Tentativo {3}/5", pecMail.Id, mailbox.Id, mailbox.MailBoxName, i + 1), ex); // Attendo 1 minuto prima di riprovare #if !DEBUG Thread.Sleep(1000 * 30); #endif } finally { // Procedo i++; } } // Se dopo 5 tentativi ancora non ha ricevuto conferma di spedizione allora invio una mail e blocco l'invio if (sent) { _factory.PECMailboxLogFacade.SentMail(ref pecMail); return(true); } // Errori String errorMessages = string.Format("Errori di invio:{0}", Environment.NewLine); errorMessages = sendResult.GeneralErrors.Aggregate(errorMessages, (current, generalError) => current + string.Format("Code:{1} - Message:{2} - Status:{3}{0}", Environment.NewLine, generalError.Code, generalError.Message, generalError.Status)); _factory.PECMailboxLogFacade.SentErrorMail(ref pecMail, new Exception(errorMessages)); pecMail.IsActive = ActiveType.Cast(ActiveType.PECMailActiveType.Error); _factory.PECMailFacade.UpdateOnly(ref pecMail); String errorResult = string.Format("La PEC {0} / casella {1} - {2} non è stata spedita dopo 5 tentativi falliti. \nE' stata pertanto disattivata (isActive = 255) per evitare ulteriori tentativi.", pecMail.Id, mailbox.Id, mailbox.MailBoxName); _factory.PECMailLogFacade.Error(ref pecMail, errorResult); _factory.PECMailLogFacade.Error(ref pecMail, string.Concat(errorResult, errorMessages)); MailStoreFacade.SetPECMailTaskError(pecMail); throw new Exception(errorResult, lastException); }