public async void btnSend_Click(object sender, RoutedEventArgs e) { MailBuilder myMail = new MailBuilder(); myMail.Html = problem.Text; myMail.Subject = subject.Text; myMail.To.Add(new MailBox(txtemail.Text)); myMail.From.Add(new MailBox(subject.Text)); IMail email = myMail.Create(); try { using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.mail.yahoo.com.hk",465); await smtp.UseBestLoginAsync("*****@*****.**", "tyive123"); await smtp.SendMessageAsync(email); await smtp.CloseAsync(); MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); await msg.ShowAsync(); } } catch (Exception ex) { MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); msg.ShowAsync(); } }
// this code is used for the SMTPAPI examples private static void Main() { // Create the email object first, then add the properties. SendGridMessage myMessage = MailBuilder.Create() .To("*****@*****.**") .From(new MailAddress("*****@*****.**", "John Smith")) .Subject("Testing the SendGrid Library") .Text("Hello World!") .Build(); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential("username", "password"); // Create a Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. if (transportWeb != null) { transportWeb.DeliverAsync(myMessage); } Console.WriteLine("Done!"); Console.ReadLine(); }
private async void btnSend_Click(object sender, RoutedEventArgs e) { for (int i = 0; i < 100; i++) { MailBuilder mb = new MailBuilder(); mb.From.Add(new MailBox(txtFrom.Text)); mb.To.Add(new MailBox(txtTo.Text)); mb.Subject = txtSubject.Text; mb.Html = txtBody.Text; if (file != null) { await mb.AddAttachment(file); } IMail mail = mb.Create(); try { Smtp smtp = new Smtp(); await smtp.Connect("smtp.gmail.com", 587); await smtp.UseBestLoginAsync(txtFrom.Text, txtPasscode.Password); await smtp.SendMessageAsync(mail); await smtp.CloseAsync(); } catch (Exception ex) { new MessageDialog(ex.Message).ShowAsync(); //throw; } } await new MessageDialog("Send mail completed").ShowAsync(); }
static void send(string subject, User to) { try { MailBuilder builder = new MailBuilder(); builder.Html = @"Html with an image: <img src=""cid:lena"" />"; builder.Subject = subject; MimeData visual = builder.AddVisual(HostingEnvironment.MapPath("~/Images/logo_2.png")); visual.ContentId = "lena"; MimeData attachment = builder.AddAttachment(@"C:\Users\User\Desktop\Attachment.txt"); attachment.FileName = "document.doc"; builder.From.Add(new MailBox("*****@*****.**")); builder.To.Add(new MailBox(to.Email)); //builder.To.Add(new MailBox("*****@*****.**")); IMail email = builder.Create(); using (Smtp smtp = new Smtp()) { smtp.Connect(_server); // or ConnectSSL for SSL smtp.UseBestLogin(_user, _password); smtp.SendMessage(email); smtp.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); } }
private async void btnSend_Click(object sender, RoutedEventArgs e) { MailBuilder myMail = new MailBuilder(); string message = string.Empty; txtMessage.Document.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out message); myMail.Html = message; myMail.Subject = txtSubject.Text; await myMail.AddAttachment(AttachFile); myMail.To.Add(new MailBox(txtTo.Text)); myMail.From.Add(new MailBox(txtFrom.Text)); myMail.Cc.Add(new MailBox(txtCC.Text)); myMail.Bcc.Add(new MailBox(txtBCc.Text)); IMail email = myMail.Create(); using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.gmail.com", 587); await smtp.UseBestLoginAsync("*****@*****.**", "Osxunix97"); await smtp.SendMessageAsync(email); await smtp.CloseAsync(); await new MessageDialog("mail send success").ShowAsync(); } }
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(); } }
public void SendMessage() { try { XElement element = XElement.Load("MailSettings.xml"); MailBuilder builder = new MailBuilder(); //builder.Subject = String.Format("{0} - {1}", themeTxb.Text, SendMail.MailSettings.SenderName); builder.Subject = themeTxb.Text + " - " + element.Element("GeneralInformation").Element("senderName").Value; //builder.Subject = themeTxb.Text + " - " + SendMail.MailSettings.SenderName; builder.From.Add(new MailBox(element.Element("GeneralInformation").Element("email").Value, element.Element("GeneralInformation").Element("email").Value)); //builder.From.Add(new MailBox(SendMail.MailSettings.Email)); builder.To.Add(new MailBox(whomTxb.Text)); builder.Text = contentTxb.Text; if (attachBtnFlag == true) { foreach (var i in pathFileName) { builder.AddAttachment(i); } } IMail email = builder.Create(); using (Smtp smtp = new Smtp()) { smtp.ConnectSSL(element.Element("SendingMail").Element("sendingMail").Value); //smtp.ConnectSSL(SendMail.MailSettings.SendingMail); smtp.Configuration.EnableChunking = true; smtp.UseBestLogin(element.Element("SendingMail").Element("sendingLogin").Value, element.Element("SendingMail").Element("sendingPassword").Value); //smtp.UseBestLogin(SendMail.MailSettings.SendingLogin, SendMail.MailSettings.SendingPassword); smtp.SendMessage(email); MessageBox.Show("Електронний лист успішно надіслано!"); } using (Imap imap = new Imap()) { imap.ConnectSSL(element.Element("ReceivingMail").Element("receivingMail").Value); //imap.ConnectSSL(SendMail.MailSettings.ReceivingMail); imap.UseBestLogin(element.Element("ReceivingMail").Element("receivingLogin").Value, element.Element("ReceivingMail").Element("receivingPassword").Value); //imap.UseBestLogin(SendMail.MailSettings.ReceivingLogin, SendMail.MailSettings.ReceivingPassword); CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.UploadMessage(folders.Sent, email); imap.Close(); } } catch (IOException ex) { MessageBox.Show(ex.Message); } }
public IActionResult BlogNotificationMailSend(int id) { try { var setting = settingRepository.GetById(1); var emailList = emailRegRepository.GetAll().Select(p => p.EmailAddress).ToList(); var blog = blogRepository.GetById(id); string messageHtml = "" + "<div style='background-color:#F7F7F7;padding:5px;'>" + "<div style='background-color:#FFF;padding:5px;'>" + "<h3 style='text-align:center'>" + blog.Title + "</h3>" + "<p style='text-align:center'><img src='https://" + setting.SiteName + "/img/" + blog.ImageUrl + "' width='400px'/></p>" + "<p style='text-align:justify'>" + blog.Explanation + "...</p>" + "<a href='https://" + setting.SiteName + "/Home/Detail/" + blog.BlogId + "' style='text-decoration:none;text-align:center;display:block; background-color:#007bff;color:#fff;padding:10px 15px;border-radius:15px'>Makeleye Git</a>" + "<hr/>" + "<p>E-Posta aboneliğimizden çıkmak için <a href='https://" + setting.SiteName + "/Home/EmailCancellation'>buraya tıklayarak</a> ilgili adrese gidiniz.</p>" + "</div>" + "</div>"; MailBuilder builder = new MailBuilder(); builder.From.Add(new MailBox(setting.SMTPServerFrom, setting.SMTPServerFromName)); builder.To.Add(new MailGroup("Undisclosed recipients")); foreach (string item in emailList) { builder.Bcc.Add(new MailBox(item)); } builder.Subject = blog.Title; builder.Html = messageHtml; IMail email = builder.Create(); using Smtp smtp = new Smtp(); smtp.Connect(setting.SMTPServerHost, Convert.ToInt32(setting.SMTPServerPort)); // or ConnectSSL for SSL smtp.UseBestLogin(setting.SMTPServerUsername, setting.SMTPServerPassword); // remove if not needed smtp.SendMessage(email); smtp.Close(); blog.IsMailSend = true; if (blogRepository.UpdateBlog(blog)) { TempData["MailNotificationSuccess"] = "'" + blog.Title + "', bloğu için e-posta bildirimleri gönderildi."; } } catch { TempData["MailNotificationDanger"] = "E-Posta bildirimi gönderilirken bir hata oluştu!"; } return(RedirectToAction("List")); }
public IActionResult GetEmailControlCode(EmailRegistration emailCancell) { string postResultString; int messageNumber; var emailCancelled = emailRegRepository.GetAll().Where(p => p.EmailAddress == emailCancell.EmailAddress); if (emailCancelled.Any()) { if (ModelState.IsValid) { var setting = settingRepository.GetById(1); string messageHtml = "" + "<div style='background-color:#F7F7F7;padding:5px;'>" + "<div style='background-color:#FFF;padding:5px;'>" + "<p>Kontrol Kodunuz: " + emailCancelled.First().ControlCode + "</p>" + "</div>" + "</div>"; MailBuilder builder = new MailBuilder(); builder.From.Add(new MailBox(setting.SMTPServerFrom, setting.SMTPServerFromName)); builder.To.Add(new MailBox(emailCancell.EmailAddress)); builder.Subject = "Abonelik İptali İçin Kontrol Kodu"; builder.Html = messageHtml; IMail email = builder.Create(); using Smtp smtp = new Smtp(); smtp.Connect(setting.SMTPServerHost, Convert.ToInt32(setting.SMTPServerPort)); // or ConnectSSL for SSL smtp.UseBestLogin(setting.SMTPServerUsername, setting.SMTPServerPassword); // remove if not needed smtp.SendMessage(email); smtp.Close(); postResultString = "Kontrol kodu, e-posta adresinize gönderildi."; messageNumber = 2; } else { postResultString = "Kontrol kodu gönderilirken bir hata oluştu! Lütfen daha sonra tekrar deneyiniz veya iletişime geçiniz."; messageNumber = 3; } } else { postResultString = "Girilen e-posta adresi için bir kayıt bulunamadı! Lütfen doğru bilgileri girdiğinizden emin olunuz."; messageNumber = 1; } return(new JsonResult(new { message = postResultString, messageType = messageNumber })); }
private async void SendBtn_Click(object sender, RoutedEventArgs e) { MailBuilder myMail = new MailBuilder(); myMail.Html = MsgText.Text; myMail.Subject = SubText.Text; await myMail.AddAttachment(AttachFile); myMail.To.Add(new MailBox(ToText.Text)); myMail.From.Add(new MailBox(FromText.Text)); IMail email = myMail.Create(); try { using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.gmail.com", 587); await smtp.UseBestLoginAsync(USER, PASSWORD); await smtp.SendMessageAsync(email); await smtp.CloseAsync(); MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); msg.ShowAsync(); } } catch (Exception ex) { MessageDialog msg = new MessageDialog("Error in mail send"); msg.ShowAsync(); } }
private async void btnSend(object sender, RoutedEventArgs e) { MailBuilder myMail = new MailBuilder(); myMail.Html = txtContent.Text; myMail.Subject = txtSubject.Text; await myMail.AddAttachment(AttachFile); myMail.To.Add(new MailBox(txtTo.Text)); myMail.From.Add(new MailBox(MainPage.email)); IMail email = myMail.Create(); try { using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.gmail.com", 587); await smtp.UseBestLoginAsync(MainPage.email, MainPage.password); await smtp.SendMessageAsync(email); await smtp.CloseAsync(); MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); msg.ShowAsync(); } } catch (Exception ex) { MessageDialog msg = new MessageDialog("Can not send mail! " + ex.Message); msg.ShowAsync(); } }
/// <summary> /// Build email from MailBuilder using interface IMail, pass to SendMail() /// </summary> /// <param name="sendTo">Recipient</param> /// <param name="sendSubject">Subject</param> /// <param name="sendMailContents">Body</param> /// <param name="sendFrom">Sender</param> public void ProcessMailToSend(string sendTo, string sendSubject, string sendMailContents, string sendFrom) { // Append scalemail signature sendMailContents += "<br/>Sent using <img src=\"http://i42.photobucket.com/albums/e333/rcastoro1/scalemailSignature_zpse308b52b.gif \" border=\"0\" alt=\" photo scalemailSignature_zpse308b52b.gif\"/> v1.0 ^-^"; MailBuilder builder = new MailBuilder(); builder.From.Add(new MailBox(sendFrom, "")); builder.To.Add(new MailBox(sendTo, "")); builder.Subject = sendSubject; builder.Html = sendMailContents; foreach (string attachment in _attachmentList) { MimeData attach = builder.AddAttachment(attachment); } IMail email = builder.Create(); SendMail(email); }
public static IMail MapToIMail(Email message) { var builder = new MailBuilder(); ProcessEmailAddresses(builder, message.EmailAddresses); builder.Subject = message.Subject; builder.Text = message.PlainTextBody; builder.PriorityHigh(); if (!string.IsNullOrEmpty(message.HtmlBody)) builder.Html = message.HtmlBody; foreach (var ea in message.Attachments) { var attachment = builder.AddAttachment(ea.ByteArray); attachment.FileName = ea.AttachmentName; attachment.ContentType = ContentType.Parse(ea.MimeType); } return builder.Create(); }
//public void SendMessage() //{ // try // { // MailAddress fromMailAddress = new MailAddress("*****@*****.**"); // MailAddress toAddress = new MailAddress("*****@*****.**"); // using (MailMessage mailMessage = new MailMessage(fromMailAddress, toAddress)) // using (SmtpClient smtpClient = new SmtpClient("smtp.ukr.net", 465)) // { // mailMessage.Subject = "Test Email"; // mailMessage.Body = "Helllllooo!!!"; // smtpClient.Credentials = new NetworkCredential(fromMailAddress.Address, "kdocument_2021"); // smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; // smtpClient.EnableSsl = true; // smtpClient.UseDefaultCredentials = false; // smtpClient.Send(mailMessage); // MessageBox.Show("Email sent successfully!"); // } // } // catch (IOException ex) // { // MessageBox.Show(ex.Message); // } //} public void TestSendMessage() { try { MailBuilder builder = new MailBuilder(); builder.Subject = String.Format("Тестовий лист - {0}", senderNameCmb.Text); builder.From.Add(new MailBox(emailTxb.Text, emailTxb.Text)); builder.To.Add(new MailBox(emailTxb.Text)); builder.Text = "Це електронний лист із простим текстом"; IMail email = builder.Create(); using (Smtp smtp = new Smtp()) { smtp.ConnectSSL(sendingMailTxb.Text); smtp.Configuration.EnableChunking = true; smtp.UseBestLogin(sendingLoginCmb.Text, sendingPasswordTxb.Text); smtp.SendMessage(email); MessageBox.Show("Електронний лист успішно надіслано!"); } using (Imap imap = new Imap()) { imap.ConnectSSL(receivingMailTxb.Text); imap.UseBestLogin(receivingLoginCmb.Text, receivingPasswordTxb.Text); CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.UploadMessage(folders.Sent, email); imap.Close(); } } catch (IOException ex) { MessageBox.Show(ex.Message); } }
public async void btnSend_Click(object sender, RoutedEventArgs e) { MailBuilder myMail = new MailBuilder(); myMail.Html = problem.Text; myMail.Subject = subject.Text; myMail.To.Add(new MailBox(txtemail.Text)); myMail.From.Add(new MailBox(subject.Text)); IMail email = myMail.Create(); try { using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.mail.yahoo.com.hk", 465); await smtp.UseBestLoginAsync("*****@*****.**", "tyive123"); await smtp.SendMessageAsync(email); await smtp.CloseAsync(); MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); await msg.ShowAsync(); } } catch (Exception ex) { MessageDialog msg = new MessageDialog("Mail has been sucessfully sent"); msg.ShowAsync(); } }
public static async Task <SendMailResult> SendTestMail() { var templateConfig = new TemplateServiceConfiguration(); var templateFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "EmailTemplates"); templateConfig.TemplateManager = new ResolvePathTemplateManager(new string[] { templateFolder }); var templateService = RazorEngineService.Create(templateConfig); return(await MailBuilder.Create(templateService) .Configure.SMTPServer("localhost") .Done .From("*****@*****.**", "Tobias Jansäter") .WithHeader("test", "sdfsdf") .WithSubject("Some subject") .AndTemplate("SampleTemplate.cshtml", new { Name = "Test User" }) //.AddMeeting(new Meeting(DateTime.Now.AddHours(1), DateTime.Now.AddHours(3)) //{ // Description = "Do you know what the next step should be for TypeLess.Mail?", // Location = "The usual place", // Summary = "We need to go through some new features" //}) .To(new Contact("*****@*****.**", ContactType.To)) .SendAsync()); }
/// <summary> /// Uses SMTP to send an email through Mail.dll with the paramenters below. Returns whether it sent successfully /// </summary> /// <param name="HostServer"></param> /// <param name="HostUName"></param> /// <param name="HostPass"></param> /// <param name="SpoofFrom"></param> /// <param name="SpoofName"></param> /// <param name="ToAddress"></param> /// <param name="Subject"></param> /// <param name="Body"></param> /// <returns></returns> public bool SendEmail(string HostServer, string HostUName, string HostPass, string SpoofFrom, string SpoofName, string ToAddress, string Subject, string Body) { //The following 5 lines set up the email itself. MailBuilder Builder = new MailBuilder(); Builder.From.Add(new MailBox(SpoofFrom, SpoofName)); Builder.To.Add(new MailBox(ToAddress)); Builder.Subject = Subject; Builder.Html = Body; //The following section creates the email and then sends the email IMail Email = Builder.Create(); using (Smtp smtp = new Smtp()) { //the next three lines defines a local variable and then logs into mail server. For security reasons //I have omitted the password from the login line. bool Success; smtp.ConnectSSL(HostServer); smtp.UseBestLogin(HostUName, HostPass); //This section attempts to send the email and returns whether it manages to send an email successfully. SendMessageResult Result = smtp.SendMessage(Email); if (Result.Status == SendMessageStatus.Success) { Success = true; } else { Success = false; } smtp.Close(); return(Success); } }
private void AddMessageToDrafts(string to, string subject, string rtf) { MailBuilder mailBuilder = new MailBuilder(); try { mailBuilder.From.Add(new MailBox(this.EmailBox.EmailAddress)); } catch (Exception) { return; } mailBuilder.To.Add(new MailBox(to)); mailBuilder.Subject = subject; mailBuilder.Rtf = rtf; for (int i = 0; i < this.Attachments.Count; i++) { MimeData mime = mailBuilder.AddAttachment(this.Attachments[i]); mime.FileName = (string)this.attachmentsListBox.Items[i]; } this.EmailBox.UploadMessageToDrafts(mailBuilder.Create()); }
public byte[] Send(MailMessage message, bool returnBlob = false, bool needDispositionNotification = false, StandardMailAddress notificationTo = null) { // Gestore dei messaggi MailBuilder builder = new MailBuilder { MessageID = Guid.NewGuid().ToString(), Subject = message.Subject }; // Creo il messaggio base builder.From.Add(new MailBox(message.From.Address, message.From.DisplayName)); builder.Text = message.Body; builder.Html = message.Body.Replace(Environment.NewLine, "<br />"); // Carico i destinatari A foreach (var recipient in message.To) { builder.To.Add(new MailBox(recipient.Address, recipient.DisplayName)); } // Carico i destinatari CC foreach (var recipient in message.CC) { builder.Cc.Add(new MailBox(recipient.Address, recipient.DisplayName)); } //Specifico se notificare al mittente la notifiche di lettura e ricezione if (needDispositionNotification && notificationTo != null) { MailBox originalSender = new MailBox(notificationTo.Address, notificationTo.DisplayName); builder.RequestReadReceipt(); builder.NotificationTo.Clear(); builder.ReplyTo.Clear(); builder.ReturnReceiptTo.Clear(); builder.NotificationTo.Add(originalSender); builder.ReturnReceiptTo.Add(originalSender); } // Carico gli allegati foreach (var attachment in message.Attachments) { var mime = new MimeFactory().CreateMimeData(); using (var ms = new MemoryStream()) { attachment.ContentStream.CopyTo(ms); mime.Data = ms.ToArray(); } mime.ContentType = ContentType.Parse(attachment.Name.GetMimeType()); mime.FileName = attachment.Name; builder.AddAttachment(mime); } // Priorità switch (message.Priority) { case MailPriority.Low: builder.Priority = MimePriority.NonUrgent; break; case MailPriority.Normal: builder.Priority = MimePriority.Normal; break; case MailPriority.High: builder.Priority = MimePriority.Urgent; break; } // Genero la mail da spedire var email = builder.Create(); var sent = false; var i = 0; Exception lastException = null; while (!sent && i < 5) { using (var smtp = new Smtp()) { // Accetto anche i certificati non validi smtp.ServerCertificateValidate += ServerCertificateValidateCallBack; // Connessione al server smtp.Connect(_server, _port, AuthenticationType == MailClient.AuthenticationType.Ssl); // Attivazione Tls, se richiesta if (AuthenticationType == MailClient.AuthenticationType.Tls) { smtp.StartTLS(); } // Login, se necessario if (!UseDefaultCredentials) { smtp.UseBestLogin(Credentials.UserName, Credentials.Password); } // Imposto il timeout per la richiesta smtp.SendTimeout = new TimeSpan(0, 0, 0, 0, Timeout); // Invio e calcolo il risultato var messageResult = smtp.SendMessage(email); sent = (messageResult.Status == SendMessageStatus.Success); try { smtp.Close(true); } catch (Exception ex) { lastException = ex; } } if (!sent) { Thread.Sleep(1000 * 30); continue; } i++; } if (returnBlob && email != null) { byte[] eml = email.Render(); return(eml); } if (!sent && lastException != null) { throw new Exception("Impossibile inviare il messaggio dopo 5 tentativi.", lastException); } return(null); }
private void SendButton_Click(object sender, RoutedEventArgs e) { if (this.encryptMessage.IsChecked == true && this.EmailBox.XmlStringChipherKeyContainerName is null) { MessageBox.Show("Для шифрования сообщения следует импортировать открытый ключ!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (this.toTextBox.Text is null) { MessageBox.Show("Требуется ввести имя получателя.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } MailBuilder mailBuilder = new MailBuilder(); mailBuilder.From.Add(new MailBox(this.EmailBox.EmailAddress)); try { mailBuilder.To.Add(new MailBox(this.toTextBox.Text.Trim(' '))); } catch (ArgumentException) { MessageBox.Show("Имя получателя написано в неверном формате.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); return; } mailBuilder.Subject = this.subjectTextBox.Text.Trim(' '); if (encryptMessage.IsChecked == true) { byte[] data = this.GetBytesFromRichTextBoxText(this.textRichTextBox); byte[] encData = Encrypter.EncryptWithAesAndRsa(data, this.EmailBox.XmlStringChipherKeyContainerName, true); byte[] signedData = Encrypter.SignData(encData, this.EmailBox.UserKeyContainerName); mailBuilder.Rtf = Convert.ToBase64String(signedData); } else { mailBuilder.Rtf = this.GetTextFromRichTextBox(this.textRichTextBox); } for (int i = 0; i < this.Attachments.Count; i++) { if (encryptMessage.IsChecked == true) { byte[] data = this.Attachments[i]; byte[] encData = Encrypter.EncryptWithAesAndRsa(data, this.EmailBox.XmlStringChipherKeyContainerName, true); byte[] signedData = Encrypter.SignData(encData, this.EmailBox.UserKeyContainerName); MimeData mime = mailBuilder.AddAttachment(signedData); mime.FileName = (string)this.attachmentsListBox.Items[i]; } else { MimeData mime = mailBuilder.AddAttachment(this.Attachments[i]); mime.FileName = (string)this.attachmentsListBox.Items[i]; } } IMail mail = mailBuilder.Create(); if (sendThread != null && sendThread.IsAlive) { sendThread.Abort(); sendThread.Join(); } sendThread = new Thread(() => { this.Dispatcher.Invoke(() => { this.sendButton.IsEnabled = false; Mouse.OverrideCursor = Cursors.AppStarting; }); this.EmailBox.Smtp.SendMessage(mail); this.Dispatcher.Invoke(() => { this.Close(); this.sendButton.IsEnabled = true; Mouse.OverrideCursor = null; }); }); sendThread.Start(); }
private IMail GetMailMessage(Guid guid, PECMail pecMail) { MailBuilder builder = new MailBuilder(); foreach (MailBox mailBox in MailStringToList(pecMail.MailSenders)) { builder.From.Add(mailBox); } foreach (MailBox mailBox in MailStringToList(pecMail.MailRecipients)) { builder.To.Add(mailBox); } foreach (MailBox mailBox in MailStringToList(pecMail.MailRecipientsCc)) { builder.Cc.Add(mailBox); } builder.Subject = string.IsNullOrEmpty(pecMail.MailSubject) ? string.Empty : StringHelper.ReplaceCrLf(pecMail.MailSubject); // Crea il corpo del messaggio di default (non è richiesto dall'Interoperabilità) o lo legge da base dati, se indicato builder.Text = (string.IsNullOrEmpty(pecMail.MailBody)) ? string.Format("Invio protocollo \"{0}\" ({1}/{2})", pecMail.MailSubject, pecMail.Number, pecMail.Year) : pecMail.MailBody; builder.MessageID = guid.ToString(); if (!string.IsNullOrEmpty(pecMail.Segnatura)) { // Estrae la segnatura dalla base dati e la allega alla mail in uscita MimeData xmlSegnatura = builder.AddAttachment(Encoding.GetEncoding(1252).GetBytes(pecMail.Segnatura)); xmlSegnatura.ContentType = new ContentType(MimeType.Text, MimeSubtype.Xml); xmlSegnatura.ContentId = "Segnatura.xml"; xmlSegnatura.FileName = "Segnatura.xml"; } // Estrae i relativi allegati da base dati (documento ed allegati) if ((pecMail.Attachments != null) && (pecMail.Attachments.Count > 0)) { byte[] attachmentByteArray; foreach (PECMailAttachment attachment in pecMail.Attachments) { try { attachmentByteArray = null; string attachmentName = FileHelper.ReplaceUnicode(FileHelper.ConvertUnicodeToAscii(attachment.AttachmentName)); if (pecMail.Location != null && !string.IsNullOrEmpty(pecMail.Location.DocumentServer) && attachment.IDDocument != Guid.Empty) { // Allora utilizzo l'idDocument BiblosDocumentInfo doc = new BiblosDocumentInfo(pecMail.Location.DocumentServer, attachment.IDDocument); attachmentByteArray = doc.Stream; FileLogger.Debug(_loggerName, string.Format("Caricamento allegato {0} della PEC {1} inserito da DSW8 utilizzando l'IDDocument", attachmentName, pecMail.Id)); } else { throw new Exception("L'allegato non contiene nè un idBiblos valido nè uno stream valido e pertanto non può essere inviato."); } MimeData document = builder.AddAttachment(attachmentByteArray); if (attachmentName.EndsWith(FileHelper.EML, StringComparison.InvariantCultureIgnoreCase)) { document.ContentType = new ContentType(MimeType.Message, MimeSubtype.Rfc822); } else { document.ContentType = new ContentType(MimeType.Application, MimeSubtype.OctetStream); } document.ContentId = attachmentName; document.FileName = attachmentName; } catch (Exception ex) { FileLogger.Error(_loggerName, string.Format("Errore in aggiunta allegati alla PECMail [{0}].", pecMail.Id), ex); } } } // Estrae il messaggio di ritorno dalla base dati, se presente e lo allega alla mail in uscita if (pecMail.MessaggioRitornoName != null && pecMail.MessaggioRitornoStream != null) { MimeData messaggioRitornoStream = builder.AddAttachment(Encoding.GetEncoding(1252).GetBytes(pecMail.MessaggioRitornoStream)); messaggioRitornoStream.ContentType = new ContentType(MimeType.Text, MimeSubtype.Xml); messaggioRitornoStream.ContentId = pecMail.MessaggioRitornoStream; messaggioRitornoStream.FileName = pecMail.MessaggioRitornoStream; } if (pecMail.MailPriority.HasValue) { switch (pecMail.MailPriority) { case -1: builder.Priority = MimePriority.NonUrgent; break; case 1: builder.Priority = MimePriority.Urgent; break; default: builder.Priority = MimePriority.Normal; break; } } else { builder.Priority = MimePriority.Normal; } return(builder.Create()); }
public void DisplayNameDoesNotThrowException(string to, string from, string subject, string body, string displayName) { MailBuilder.Create(to, from, subject, body, displayName); }
/// <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); }
public void Test_Method1() { var mail = MailBuilder.Create() .Build(); }
private async void btnPost_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { ProgBar.IsIndeterminate = true; EnableControl(false); if (txtBoxContent.Text != "") { string Content = "From: " + txtBoxFrom.Text + Environment.NewLine //New line + "To: " + txtBoxTo.Text + Environment.NewLine + Environment.NewLine + "Content: " + Environment.NewLine + txtBoxContent.Text + Environment.NewLine + Environment.NewLine + "Sent from Nguyen An Ninh Confession App for Windows Phone :)"; MailBuilder myMail = new MailBuilder(); myMail.Text = Content; myMail.Subject = "New Confession from Windows Phone app - From " + txtBoxFrom.Text + " - To " + txtBoxTo.Text; //await myMail.AddAttachment(attachFile); myMail.To.Add(new MailBox("*****@*****.**")); myMail.From.Add(new MailBox("*****@*****.**")); IMail email = myMail.Create(); try { using (Smtp smtp = new Smtp()) { await smtp.Connect("smtp.example.com", 25); //Change smtp address and port await smtp.StartTLS(); await smtp.UseBestLoginAsync("*****@*****.**", "ExamplePassword"); //Change email credentials information await smtp.SendMessageAsync(email); await smtp.CloseAsync(); var msg = new MessageDialog("Your confession has been successfully sent!").ShowAsync(); ProgBar.IsIndeterminate = false; EnableControl(true); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); //Use this to show Exception in the Output window. var msgDialog = new MessageDialog("Please try again :(", "Failed to post").ShowAsync(); ProgBar.IsIndeterminate = false; EnableControl(true); } } else { var msgDialog = new MessageDialog("Put something in before sending.", "Nothing to send").ShowAsync(); EnableControl(true); } }
private void startprocess(string logindetails, string imapselect, bool sendmail, string smtptet) { try { int type = 0; Socket socket = null; if (proxies.Count > 0) { type = 1; ProxyFactory factory = new ProxyFactory(); string proxi = proxies[rad.Next(proxies.Count)]; string[] prox = proxi.Split(':'); IProxyClient proxy = null; if (prox.Length == 4) { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]); } else { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1])); } socket = proxy.Connect(imapselect, Imap.DefaultSSLPort); } using (Imap imap = new Imap()) { if (type == 0) { imap.ConnectSSL(imapselect); } else { imap.AttachSSL(socket, imapselect); } string[] cred = logindetails.Split(':'); imap.Login(cred[0], cred[1]); // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods, CommonFolders folders = new CommonFolders(imap.GetFolders()); imap.Select(folders.Spam); foreach (long ouid in imap.GetAll()) { IMail email = new MailBuilder().CreateFromEml( imap.GetMessageByUID(ouid)); List <long> unseenReports = new List <long>(); foreach (string sub in subjects) { if (email.Subject.Contains(sub) || string.Equals(email.Subject, sub)) { unseenReports.Add(ouid); if (!checkBox1.Checked && sendmail && !radioButton4.Checked) { IMail original = email; Socket socket1 = null; if (proxies.Count > 0) { type = 1; ProxyFactory factory = new ProxyFactory(); string proxi = proxies[rad.Next(proxies.Count)]; string[] prox = proxi.Split(':'); IProxyClient proxy = null; if (prox.Length == 4) { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]); } else { proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1])); } socket1 = proxy.Connect(smtptet, portsmtp); } ReplyBuilder replyBuilder = original.Reply(); // You can specify your own, custom, body and subject templates: replyBuilder.HtmlReplyTemplate = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""> <html> <head> <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" /> <title>[Subject]</title> </head> <body> [Html] <br /><br /> On [Original.Date] [Original.Sender.Name] wrote: <blockquote style=""margin-left: 1em; padding-left: 1em; border-left: 1px #ccc solid;""> [QuoteHtml] </blockquote> </body> </html>"; replyBuilder.SubjectReplyTemplate = "Re: [Original.Subject]"; replyBuilder.Html = NewSpin.Spin(textBox1.Text); MailBuilder builder = replyBuilder.ReplyToAll(cred[0]); // You can add attachments to your reply //builder.AddAttachment("report.csv"); IMail reply = builder.Create(); using (Smtp smtp = new Smtp()) { if (type == 0) { if (radioButton3.Checked || radioButton4.Checked) { smtp.Connect(smtptet, portsmtp); smtp.StartTLS(); } else { smtp.ConnectSSL(smtptet, portsmtp); } } else { if (radioButton3.Checked || radioButton4.Checked) { smtp.Attach(socket1); smtp.StartTLS(); } else { smtp.AttachSSL(socket1, smtptet); } } smtp.ReceiveTimeout = new TimeSpan(0, 0, 100); //MessageBox.Show("Sending Mail"); smtp.UseBestLogin(cred[0], cred[1]); smtp.SendMessage(reply); smtp.Close(); } } } } foreach (long uid in unseenReports) // Download emails from the last result. { // MessageBox.Show(uid.ToString()); imap.MoveByUID(uid, folders.Inbox); imap.FlagMessageByUID(uid, Flag.Seen); movedcount = movedcount + 1; } } imap.Close(); } } catch (Exception exp) { //MessageBox.Show(exp.ToString()); } finally { count = count + 1; } }
private void sendMail(Message _message) { if (_message == null) { return; } if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Server)) { return; } Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Start to send mail"); //Check settings if (Settings.Default.MailOutput_Port <= 0) { throw new ArgumentNullException("MailOutput_Port"); } if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Sender)) { throw new ArgumentNullException("MailOutput_Sender"); } if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_User)) { throw new ArgumentNullException("MailOutput_User"); } if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Password)) { throw new ArgumentNullException("MailOutput_Password"); } //Settings var _senderMailbox = new MailBox(Settings.Default.MailOutput_Sender, "Rescue-Information-System"); var _mailBuilder = new MailBuilder(); _mailBuilder.From.Add(_senderMailbox); _mailBuilder.Subject = _message.Subject; _mailBuilder.Text = _message.Text; //Werbung for (var i = 0; i < 5; i++) { _mailBuilder.Text += Environment.NewLine; } _mailBuilder.Text += "RIS by www.srs-software.de"; //Empfänger hinzufügen foreach (var _user in _message.Recivers) { if (!isValidEmail(_user.MailAdresse)) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"User {_user.Name} -> mail address not valid"); continue; } var _newAdress = new MailBox(_user.MailAdresse, _user.Name); _mailBuilder.Bcc.Add(_newAdress); Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"User add ({_user.Name})"); } if (_mailBuilder.Bcc.Count <= 0) { Logger.WriteDebug(MethodBase.GetCurrentMethod(), "cancel no recipients"); return; } //Anhang if (!string.IsNullOrEmpty(_message.AttachmentPath)) { if (File.Exists(_message.AttachmentPath) && WaitFileReady.Check(_message.AttachmentPath)) { _mailBuilder.AddAttachment(_message.AttachmentPath); } else { Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"{_message.AttachmentPath} -> not found"); } } //send mail Logger.WriteDebug(MethodBase.GetCurrentMethod(), "start sending"); using (var _smtpClient = new Smtp()) { if (Settings.Default.MailOutput_SSL) { _smtpClient.ConnectSSL(Settings.Default.MailOutput_Server, Settings.Default.MailOutput_Port); } else { _smtpClient.Connect(Settings.Default.MailOutput_Server, Settings.Default.MailOutput_Port); if (_smtpClient.SupportedExtensions().Contains(SmtpExtension.StartTLS)) { _smtpClient.StartTLS(); } } _smtpClient.UseBestLogin(Settings.Default.MailOutput_User, Encrypt.DecryptString(Settings.Default.MailOutput_Password, "MailOutput_Password")); Logger.WriteDebug(MethodBase.GetCurrentMethod(), "login -> ok"); var _mail = _mailBuilder.Create(); _mail.PriorityHigh(); var _result = _smtpClient.SendMessage(_mail); Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"result -> {_result}"); _smtpClient.Close(); } Logger.WriteDebug(MethodBase.GetCurrentMethod(), "send mail finished"); }