Example #1
0
        /// <summary>
        /// Sends an email asynchronously.
        /// </summary>
        /// <param name="emailMessage">The email message.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A Task.
        /// </returns>
        public Task SendAsync(IEmailMessage emailMessage, CancellationToken cancellationToken = default(CancellationToken))
        {
            Contract.Requires(emailMessage != null);
            Contract.Ensures(Contract.Result<Task>() != null);

            return Contract.Result<Task>();
        }
Example #2
0
        public async void SendEmail(IEmailMessage email)
        {
            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            if (CanSendEmail)
            {
                Tizen.Messaging.Email.EmailMessage emailMessage = new Tizen.Messaging.Email.EmailMessage();
                EmailRecipient emailRecipientTo = new EmailRecipient();
                foreach (var to in email.Recipients)
                {
                    emailRecipientTo.Address = to;
                    emailMessage.To.Add(emailRecipientTo);
                }
                emailMessage.Subject = email.Subject;
                emailMessage.Body    = email.Message;
                Tizen.Messaging.Email.EmailAttachment emailAttachment = new Tizen.Messaging.Email.EmailAttachment();
                foreach (var attachment in email.Attachments.Cast <EmailAttachment>())
                {
                    emailAttachment.FilePath = attachment.FilePath;
                    emailMessage.Attachments.Add(emailAttachment);
                }

                await EmailSender.SendAsync(emailMessage);
            }
        }
Example #3
0
        public void Send( IEmailMessage emailMessage )
        {
            var smtp = new SmtpClient
                           {
                               Credentials = new NetworkCredential( _username, _password ),
                               Host = _address,
                               Timeout = _timeoutInSeconds*1000
                           } ;

            using ( var mailMessage = new MailMessage
                                          {
                                              From = emailMessage.From,
                                              Body = emailMessage.Body,
                                              Subject = emailMessage.Subject,
                                          } )
            {
                mailMessage.To.Add( recipientsToCommaSeparatedString( emailMessage.Recipients ) );

                foreach ( string eachAttachmentPath in emailMessage.Attachments )
                {
                    mailMessage.Attachments.Add( new Attachment( eachAttachmentPath ) );
                }

                smtp.Send( mailMessage );
            }
        }
Example #4
0
        /// <summary>
        /// Adds all files on the given <paramref name="objVerEx"/> to the <paramref name="emailMessage"/>.
        /// </summary>
        /// <param name="emailMessage">The email message to add the files to.</param>
        /// <param name="objVerEx">The object version that has the files.</param>
        /// <param name="fileFormat">The format for the attached files.</param>
        public static void AddAllFiles
        (
            this IEmailMessage emailMessage,
            ObjVerEx objVerEx,
            MFFileFormat fileFormat = MFFileFormat.MFFileFormatNative
        )
        {
            // Sanity.
            if (null == emailMessage)
            {
                throw new ArgumentNullException(nameof(emailMessage));
            }
            if (null == objVerEx)
            {
                throw new ArgumentNullException(nameof(objVerEx));
            }
            if (null == objVerEx.Vault)
            {
                throw new ArgumentException("The objVerEx's vault reference is null.", nameof(objVerEx));
            }
            if (null == objVerEx.Vault)
            {
                throw new ArgumentException("The objVerEx's info (ObjectVersion) reference is null.", nameof(objVerEx));
            }

            // Use the base implementation.
            emailMessage.AddAllFiles(objVerEx.Info, objVerEx.Vault, fileFormat);
        }
        public async Task <OperationResult> SendEmail(IEmailMessage emailMessage)
        {
            try
            {
                var msg = new MailMessage
                {
                    From       = new MailAddress("*****@*****.**", "Website Contact Form"),
                    Subject    = emailMessage.Subject,
                    Body       = emailMessage.Body,
                    IsBodyHtml = emailMessage.IsBodyHtml,
                    To         =
                    {
                        emailMessage.To
                    }
                };

                var awsCredential = new AwsCredential(_awsConfig.AccessKeyId, _awsConfig.SecretKey);

                using (var client = new SesClient(AwsRegion.USEast1, awsCredential))
                {
                    var sendEmailResult = await client.SendEmailAsync(msg);

                    return(OperationResult.Ok(sendEmailResult));
                }
            }
            catch (Exception ex)
            {
                return(OperationResult.Error(ex));
            }
        }
Example #6
0
 public static async Task <(string id, Exception error)> send(IEmailMessage message)
 {
     if (_impl != null)
     {
         return(await _impl.send(message));
     }
     return(default, new NotImplementedException());
Example #7
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                // NOTE: Refer to http://www.faqs.org/rfcs/rfc2368.html for info on mailto protocol

                if (email.RecipientsBcc.Count > 0)
                    Debug.WriteLine("Bcc headers are inherently unsafe to include in a message generated from a URL - ignoring RecipientBcc");

                var sb = new StringBuilder();

                sb.AppendFormat(CultureInfo.InvariantCulture, "mailto:{0}?", ToDelimitedAddress(email.Recipients));
                
                if (email.RecipientsCc.Count > 0)
                    sb.AppendFormat(CultureInfo.InvariantCulture, "cc={0}&", ToDelimitedAddress(email.RecipientsCc));

                sb.AppendFormat(CultureInfo.InvariantCulture, "subject={0}&body={1}",
                    email.Subject, email.Message);

                var escaped = Uri.EscapeUriString(sb.ToString());

                Launcher.LaunchUriAsync(new Uri(escaped, UriKind.Absolute));
            }
        }
Example #8
0
        // Preferred method to send email.  Modify interface for new features...
        public SendEmailResponse <INotification> SendSmtpMail(IEmailMessage emailMessage)
        {
            SendEmailResponse <INotification> result = new SendEmailResponse <INotification>();

            try
            {
                using (MailMessage mailMessage = emailMessage.ToMailMessage())
                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.Send(mailMessage);
                    }
            }
            catch (SmtpException smtpException)
            {
                result.Value = new Notification(smtpException);
            }
            catch (InvalidOperationException invalidOperationException)
            {
                result.Value = new Notification(invalidOperationException);
            }
            catch (ArgumentException argumentExceptionException)
            {
                result.Value = new Notification(argumentExceptionException);
            }
            return(result);
        }
Example #9
0
        private void getMessages(int numberOfMessagesToReceive)
        {
            try
            {
                if (connectToServer())
                {
                    int numberOfMessagesOnServer = emailClient.GetMessageCount();
                    if (numberOfMessagesOnServer == 0)
                    {
                        throw new EmailServiceException("brak wiadomości na serwerze " + "emailClient.IsConnected " + emailClient.IsConnected);
                    }

                    for (int i = numberOfMessagesOnServer - 1; i >= 0 && i > (numberOfMessagesOnServer - 1 - numberOfMessagesToReceive); i--)
                    {
                        IEmailMessage emailMessage = getOneEmail(i);
                        emailsReceived.AddLast(emailMessage);
                    }
                }
            }
            catch (MailKit.Net.Pop3.Pop3ProtocolException e)
            {
                throw new EmailServiceException("Email service error", e);
            }
            catch (MailKit.ServiceNotConnectedException e)
            {
                throw new EmailServiceException("Email service error", e);
            }
        }
Example #10
0
        public virtual async Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException("emailMessage",
                                                "Supplied argument 'emailMessage' is null.");
            }

            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var task = new EmailComposeTask
            {
                To  = emailMessage.To.ToString(),
                Cc  = emailMessage.Cc.ToString(),
                Bcc = emailMessage.Bcc.ToString(),

                Subject = emailMessage.Subject,
                Body    = emailMessage.Body
            };

            task.Show();
        }
Example #11
0
 public async Task RecordEmailSent(IEmailMessage message)
 {
     if (!message.IsNew)
     {
         await Database.Delete(message);
     }
 }
Example #12
0
        /// <summary>
        /// Creates an SMTP mail message for a specified mail item.
        /// </summary>
        static async Task <MailMessage> CreateMailMessage(IEmailMessage mailItem)
        {
            if (mailItem.SendableDate > LocalTime.Now)
            {
                return(null);                                       // Not due yet
            }
            var mail = new MailMessage {
                Subject = mailItem.Subject.Or("[NO SUBJECT]").Remove("\r", "\n")
            };

            mailItem.GetEffectiveToAddresses().Do(x => mail.To.Add(x));
            mailItem.GetEffectiveCcAddresses().Do(x => mail.CC.Add(x));
            mailItem.GetEffectiveBccAddresses().Do(x => mail.Bcc.Add(x));

            if (mail.To.None() && mail.CC.None() && mail.Bcc.None())
            {
                Debug.WriteLine($"Mail message {mailItem.GetId()} will not be sent as there is no effective recipient.");
                return(null);
            }

            mail.AlternateViews.AddRange(mailItem.GetEffectiveBodyViews());

            mail.From = new MailAddress(mailItem.GetEffectiveFromAddress(), mailItem.GetEffectiveFromName());

            mail.ReplyToList.Add(new MailAddress(mailItem.GetEffectiveReplyToAddress(),
                                                 mailItem.GetEffectiveReplyToName()));

            mail.Attachments.AddRange(await mailItem.GetAttachments());

            return(mail);
        }
Example #13
0
        public bool SendMessage(IEmailMessage message)
        {
            if (!Platform.IsWindows)
            {
                return(false);
            }

            var mapi = new MAPI();

            foreach (string recipient in message.To)
            {
                Debug.Assert(!string.IsNullOrEmpty(recipient), "Email address for reporting is empty");

                mapi.AddRecipientTo(recipient);
            }
            foreach (string recipient in message.Cc)
            {
                mapi.AddRecipientCc(recipient);
            }
            foreach (string recipient in message.Bcc)
            {
                mapi.AddRecipientBcc(recipient);
            }
            foreach (string attachmentFilePath in message.AttachmentFilePath)
            {
                mapi.AddAttachment(attachmentFilePath);
            }
            //this one is better if it works (and it does for Microsoft emailers), but
            //return mapi.SendMailDirect(message.Subject, message.Body);

            //this one works for thunderbird, too. It opens a window rather than just sending:
            return(mapi.SendMailPopup(message.Subject, message.Body));
        }
Example #14
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            if (CanSendEmail)
            {
                // NOTE: Refer to http://www.faqs.org/rfcs/rfc2368.html for info on mailto protocol

                if (email.RecipientsBcc.Count > 0)
                {
                    Debug.WriteLine("Bcc headers are inherently unsafe to include in a message generated from a URL - ignoring RecipientBcc");
                }

                var sb = new StringBuilder();

                sb.AppendFormat(CultureInfo.InvariantCulture, "mailto:{0}?", ToDelimitedAddress(email.Recipients));

                if (email.RecipientsCc.Count > 0)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "cc={0}&", ToDelimitedAddress(email.RecipientsCc));
                }

                sb.AppendFormat(CultureInfo.InvariantCulture, "subject={0}&body={1}",
                                email.Subject, email.Message);

                var escaped = Uri.EscapeUriString(sb.ToString());

#pragma warning disable 4014
                Launcher.LaunchUriAsync(new Uri(escaped, UriKind.Absolute));
#pragma warning restore 4014
            }
        }
Example #15
0
        /// <summary>
        /// Will try to send the specified email and returns true for successful sending.
        /// </summary>
        public static async Task <bool> Send(IEmailMessage mailItem)
        {
            if (mailItem == null)
            {
                throw new ArgumentNullException(nameof(mailItem));
            }
            if (mailItem.Retries >= MaximumRetries)
            {
                return(false);
            }

            MailMessage mail = null;

            try
            {
                using (mail = await CreateMailMessage(mailItem))
                {
                    if (mail == null)
                    {
                        return(false);
                    }
                    return(await EmailDispatcher(mailItem, mail));
                }
            }
            catch (Exception ex)
            {
                await SendError.Raise(new EmailSendingEventArgs(mailItem, mail) { Error = ex });

                await mailItem.RecordRetry();

                Log.Error($"Error in sending an email for this EmailQueueItem of '{mailItem.GetId()}'", ex);
                return(false);
            }
        }
Example #16
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                var mail = new Windows.ApplicationModel.Email.EmailMessage
                           {
                               Subject = email.Subject, 
                               Body = email.Message
                           };

                foreach (var recipient in email.Recipients)
                {
                    mail.To.Add(new EmailRecipient(recipient));
                }
                foreach (var recipient in email.RecipientsCc)
                {
                    mail.CC.Add(new EmailRecipient(recipient));
                }
                foreach (var recipient in email.RecipientsBcc)
                {
                    mail.Bcc.Add(new EmailRecipient(recipient));
                }

                foreach (var attachment in email.Attachments.Cast<EmailAttachment>())
                {
                    mail.Attachments.Add(new Windows.ApplicationModel.Email.EmailAttachment(
                        attachment.FileName, attachment.Content));
                }

                EmailManager.ShowComposeNewEmailAsync(mail);
            }
        }
        public static string GetEmailFileName(IEmailMessage email)
        {
            string fileName;

            if (String.IsNullOrEmpty(email.Subject))
            {
                fileName = "(no name)";
            }
            else
            {
                var invalidChars = Path.GetInvalidFileNameChars();
                var chars        = email.Subject.ToCharArray();
                for (int i = 0; i < chars.Length; i++)
                {
                    for (int j = 0; j < invalidChars.Length; j++)
                    {
                        if (chars[i] == invalidChars[j])
                        {
                            chars[i] = '_';
                        }
                    }
                }
                fileName = new String(chars);
            }
            return(fileName + ".eml");
        }
Example #18
0
        public Task <OperationResult> SendEmail(IEmailMessage emailMessage)
        {
            Debug.WriteLine(emailMessage.To.ToString());
            Debug.WriteLine(emailMessage.Body);

            return(Task.FromResult(OperationResult.Ok()));
        }
Example #19
0
 private void ValidateEmailMessage(IEmailMessage emailMessage)
 {
     if (emailMessage == null)
     {
         throw new EmailMessageNotFoundException("Email Message is null and contains no information");
     }
 }
Example #20
0
		public bool SendMessage(IEmailMessage message)
		{
#if MONO
			return false;
#else
			var mapi = new MAPI();
			foreach (string recipient in message.To)
			{
				Debug.Assert(!string.IsNullOrEmpty(recipient),"Email address for reporting is empty");

				mapi.AddRecipientTo(recipient);
			}
			foreach (string recipient in message.Cc)
			{
				mapi.AddRecipientCc(recipient);
			}
			foreach (string recipient in message.Bcc)
			{
				mapi.AddRecipientBcc(recipient);
			}
			foreach (string attachmentFilePath in message.AttachmentFilePath)
			{
				mapi.AddAttachment(attachmentFilePath);
			}
			//this one is better if it works (and it does for Microsoft emailers), but
			//return mapi.SendMailDirect(message.Subject, message.Body);

			//this one works for thunderbird, too. It opens a window rather than just sending:
			return mapi.SendMailPopup(message.Subject, message.Body);
#endif
		}
Example #21
0
        /// <summary>
        /// Attaches a file to this email.
        /// </summary>
        /// <param name="this">The email queue item.</param>
        /// <param name="file">The path of the attachment file.
        /// This must be the physical path of a file inside the running application.</param>
        public static void Attach(this IEmailMessage @this, FileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var basePath = AppDomain.CurrentDomain.WebsiteRoot().FullName.ToLower();

            var path = file.FullName;

            if (path.StartsWith(basePath, caseSensitive: false)) // Relative:
            {
                path = path.Substring(basePath.Length).TrimStart("\\");
            }

            if (@this.Attachments.IsEmpty())
            {
                @this.Attachments = path;
            }
            else
            {
                @this.Attachments += "|" + path;
            }
        }
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns><c>true</c> if email sent succesfully, <c>false</c> otherwise.</returns>
        public bool SendEmail(IEmailMessage message)
        {
            if (message == null)
            {
                return(false);
            }

            //Smtp settings ?? is it OK to read setting directly here from config?
            var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

            // Create the email object first, then add the properties.
            var eMessage = SendGrid.GetInstance();

            eMessage.From = !string.IsNullOrEmpty(message.From) ? new MailAddress(message.From) : new MailAddress(smtp.From);

            // Add multiple addresses to the To field.
            eMessage.AddTo(message.To);

            eMessage.Subject = message.Subject;

            //Add the HTML and Text bodies
            eMessage.Html = message.Html;
            eMessage.Text = message.Text;

            //Add attachments
            if (message.Attachments != null && message.Attachments.Count > 0)
            {
                foreach (var attachment in message.Attachments)
                {
                    try
                    {
                        using (var stream = new MemoryStream(attachment.Length))
                        {
                            stream.Write(attachment, 0, attachment.Length);
                            stream.Position = 0;
                            eMessage.AddAttachment(stream, "file_" + message.Attachments.IndexOf(attachment));
                        }
                    }
                    catch { return(false); }
                }
            }

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential(smtp.Network.UserName, smtp.Network.Password);

            // Create an SMTP transport for sending email.
            var transportSMTP = SMTP.GetInstance(credentials, smtp.Network.Host, smtp.Network.Port);

            // Send the email.
            try
            {
                transportSMTP.Deliver(eMessage);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #23
0
        public async Task <HttpResponseMessage> SendAsync(IEmailMessage emailMessage)
        {
            using (var client = new HttpClient {
                BaseAddress = new Uri(_emailConfiguration.ApiBaseUri)
            })
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                           Convert.ToBase64String(Encoding.ASCII.GetBytes("api:" + _emailConfiguration.ApiKey)));

                var toAddresses = new List <KeyValuePair <string, string> >();
                foreach (var address in emailMessage.ToAddresses)
                {
                    toAddresses.Add(new KeyValuePair <string, string>("to", address));
                }

                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("from", _emailConfiguration.From),
                    new KeyValuePair <string, string>("subject", emailMessage.Subject),
                    new KeyValuePair <string, string>("html", emailMessage.Content)
                }.Union(toAddresses).ToArray());

                return(await client.PostAsync(_emailConfiguration.ApiBaseUri + "/messages", content).ConfigureAwait(false));
            }
        }
Example #24
0
        public void Send(IEmailMessage emailMessage)
        {
            var smtp = new SmtpClient
            {
                Credentials = new NetworkCredential(_username, _password),
                Host        = _address,
                Timeout     = _timeoutInSeconds * 1000
            };

            using (var mailMessage = new MailMessage
            {
                From = emailMessage.From,
                Body = emailMessage.Body,
                Subject = emailMessage.Subject,
            })
            {
                mailMessage.To.Add(recipientsToCommaSeparatedString(emailMessage.Recipients));

                foreach (string eachAttachmentPath in emailMessage.Attachments)
                {
                    mailMessage.Attachments.Add(new Attachment(eachAttachmentPath));
                }

                smtp.Send(mailMessage);
            }
        }
Example #25
0
        public virtual async Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException("emailMessage",
                    "Supplied argument 'emailMessage' is null.");
            }

            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var task = new EmailComposeTask
            {
                To = emailMessage.To.ToString(),
                Cc = emailMessage.Cc.ToString(),
                Bcc = emailMessage.Bcc.ToString(),
                
                Subject = emailMessage.Subject,
                Body = emailMessage.Body
            };

            task.Show();
        }
        public EnvoiFichePaieViewModel(IRegionManager regionManager,
                                       IDataTableFormExcelFileDataService dataTableFormExcelFileDataService,
                                       IDialogService dialogService,
                                       IEmailMessage emailMessage)
        {
            _logger.Debug($"-- ******** Demarrage du module ******** [Nom de la machine :] " +
                          $"{Environment.MachineName} ******* --");

            IsPreviewEmail       = false;
            IsFilePathVisible    = false;
            IsMainGridEnable     = true;
            IsProgressBarVisible = false;

            _regionManager = regionManager;
            _dialogService = dialogService;
            _emailMessage  = emailMessage;
            _dataTableFormExcelFileDataService = dataTableFormExcelFileDataService;

            _logger.Debug($"==> Debut Initialisation des commandes...");
            BrowseCommand             = new DelegateCommand(OnBrowse, CanBrowse);
            SendMailCommand           = new DelegateCommand(OnSendMail, CanSendMail); //.ObservesProperty(() => _emailMessage.ToEmail);
            SendPreviewCommand        = new DelegateCommand(OnSendPreview, CanSendPreview);
            CleerBccOrCcMailCommand   = new DelegateCommand(OnClearBccAndCcMail, CanClearBccOrCcMail);
            ChooseMailTemplateCommand = new DelegateCommand(OnChooseMailTemplate, CanChooseMailTemplate);

            _logger.Debug($"==> Fin Initialisation des commandes...");

            #region -- Thread for cut chart --
            bgWorkerExport = new BackgroundWorker();
            bgWorkerExport.WorkerReportsProgress = true;
            bgWorkerExport.DoWork             += Export_DoWork;
            bgWorkerExport.RunWorkerCompleted += Export_RunWorkerCompleted;
            bgWorkerExport.ProgressChanged    += new ProgressChangedEventHandler(this.Export_ProgressChanged);
            #endregion
        }
 public static void SendSampleEmail(this IEmailTask emailTask, IEmailMessage email)
 {
     if (emailTask.CanSendEmail)
     {
         emailTask.SendEmail(email);
     }
 }
Example #28
0
 private void AddBccAddress(IEmailMessage emailMessage, MimeMessage message)
 {
     if (emailMessage.BccAddress != null && emailMessage.BccAddress.Any())
     {
         message.Bcc.AddRange(emailMessage.BccAddress.Select(x => new MailboxAddress(x.Name, x.Address)));
     }
 }
        private void getEmails(IEmailMessage benchmarkEmail)
        {
            try
            {
                if (connectToServer())
                {
                    emailClient.Inbox.Open(FolderAccess.ReadWrite);
                    int numberOfEmailsOnServer = emailClient.Inbox.Count;

                    if (numberOfEmailsOnServer == 0)
                    {
                        throw new EmailServiceException("brak wiadomości na serwerze " + emailAccountConfiguration.receiveServer.url + " emailClient.IsConnected " + emailClient.IsConnected);
                    }

                    int           emailIndex = numberOfEmailsOnServer - 1;      //index ostatniego, tj najnowszego, maila na serwerze
                    IEmailMessage emailMessage;

                    do
                    {
                        emailMessage = getOneEmail(emailIndex);
                        tryAddToNewEmailsList(benchmarkEmail, emailMessage);
                        emailIndex--;
                    }while (conditionContinueGettingEmails(benchmarkEmail, emailMessage));
                }
            }
            catch (Exception e)
            {
                throw new EmailServiceException("Email service error", e);
            }
        }
Example #30
0
 public static void TrySend(this ISendMail sender, IEmailMessage message)
 {
     if (sender != null)
     {
         sender.Send(message);
     }
 }
Example #31
0
 public static void SendSampleEmail(this IEmailTask emailTask, IEmailMessage email)
 {
     if (emailTask.CanSendEmail)
     {
         emailTask.SendEmail(email);
     }
 }
        private void getEmails(int numberOfEmailsToReceive)
        {
            try
            {
                if (connectToServer())
                {
                    emailClient.Inbox.Open(FolderAccess.ReadOnly);
                    //testMethod();
                    int numberOfEmailsOnServer = emailClient.Inbox.Count;

                    if (numberOfEmailsOnServer == 0)
                    {
                        throw new EmailServiceException("brak wiadomości na serwerze " + emailAccountConfiguration.receiveServer.url + " emailClient.IsConnected " + emailClient.IsConnected);
                    }
                    for (int i = numberOfEmailsOnServer - 1; i >= 0 && i > (numberOfEmailsOnServer - 1 - numberOfEmailsToReceive); i--)
                    {
                        IEmailMessage emailMessage = getOneEmail(i);
                        emailsReceived.AddLast(emailMessage);
                    }
                }
            }
            catch (ImapProtocolException e)
            {
                throw new EmailServiceException("Email service error", e);
            }
            catch (MailKit.ServiceNotConnectedException e)
            {
                throw new EmailServiceException("Email service error", e);
            }
        }
Example #33
0
 public async Task SaveForFutureSend(IEmailMessage message)
 {
     if (message.IsNew)
     {
         await Database.Save(message);
     }
 }
Example #34
0
        IEnumerable <AlternateView> GetBodyViews(IEmailMessage message)
        {
            yield return(AlternateView.CreateAlternateViewFromString(
                             message.Body.RemoveHtmlTags(),
                             new ContentType("text/plain; charset=UTF-8")));

            if (message.Html)
            {
                var htmlView = AlternateView.CreateAlternateViewFromString(
                    message.Body, new ContentType("text/html; charset=UTF-8"));
                htmlView.LinkedResources.AddRange(AttachmentSerializer.GetLinkedResources(message));
                yield return(htmlView);
            }

            if (message.VCalendarView.HasValue())
            {
                var calendarType = new ContentType("text/calendar");
                calendarType.Parameters.Add("method", "REQUEST");
                calendarType.Parameters.Add("name", "meeting.ics");

                var calendarView = AlternateView
                                   .CreateAlternateViewFromString(message.VCalendarView, calendarType);
                calendarView.TransferEncoding = TransferEncoding.SevenBit;

                yield return(calendarView);
            }
        }
Example #35
0
        public virtual Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var intent = new Intent(Intent.ActionSend);

            intent.PutExtra(Intent.ExtraEmail, emailMessage.To.Select(x => x.Address).ToArray());
            intent.PutExtra(Intent.ExtraCc, emailMessage.Cc.Select(x => x.Address).ToArray());
            intent.PutExtra(Intent.ExtraBcc, emailMessage.Bcc.Select(x => x.Address).ToArray());

            intent.PutExtra(Intent.ExtraTitle, emailMessage.Subject);

            if (emailMessage.IsHTML)
            {
                intent.PutExtra(Intent.ExtraText, Html.FromHtml(emailMessage.Body));
            }
            else
            {
                intent.PutExtra(Intent.ExtraText, emailMessage.Body);
            }

            intent.SetType("message/rfc822");

            intent.StartNewActivity();

            return Task.FromResult(true);
        }
Example #36
0
        MailAddress CreateFrom(IEmailMessage message)
        {
            var address = message.FromAddress.Or(Config.From?.Address);
            var name    = message.FromName.Or(Config.From?.Name);

            return(new MailAddress(address, name));
        }
Example #37
0
        /// <summary>
        /// Creates a VCalendar text with the specified parameters.
        /// </summary>
        /// <param name="meetingUniqueIdentifier">This uniquely identifies the meeting and is used for changes / cancellations. It is recommended to use the ID of the owner object.</param>
        public static string AddVCalendarView(this IEmailMessage @this, string meetingUniqueIdentifier, DateTime start, DateTime end, string subject, string description, string location)
        {
            var dateFormat = "yyyyMMddTHHmmssZ";

            Func <string, string> cleanUp = s => s.Or("").Remove("\r").Replace("\n", "\\n");

            var r = new StringBuilder();

            r.AppendLine(@"BEGIN:VCALENDAR");
            r.AppendLine(@"PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN");
            r.AppendLine(@"VERSION:1.0");
            r.AppendLine(@"BEGIN:VEVENT");

            r.AddFormattedLine(@"DTSTART:{0}", start.ToString(dateFormat));
            r.AddFormattedLine(@"DTEND:{0}", end.ToString(dateFormat));
            r.AddFormattedLine(@"UID:{0}", meetingUniqueIdentifier);
            r.AddFormattedLine(@"SUMMARY:{0}", cleanUp(subject));
            r.AppendLine("LOCATION:" + cleanUp(location));
            r.AppendLine("DESCRIPTION:" + cleanUp(description));

            // bodyCalendar.AppendLine(@"PRIORITY:3");
            r.AppendLine(@"END:VEVENT");
            r.AppendLine(@"END:VCALENDAR");

            return(@this.VCalendarView = r.ToString());
        }
Example #38
0
        static async Task <bool> SendViaSmtp(IEmailMessage mailItem, MailMessage mail)
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.EnableSsl = mailItem.EnableSsl ?? Config.GetOrThrow("Email:EnableSsl").To <bool>();
                smtpClient.Port      = mailItem.SmtpPort ?? Config.GetOrThrow("Email:SmtpPort").To <int>();
                smtpClient.Host      = mailItem.SmtpHost.OrNullIfEmpty() ?? Config.GetOrThrow("Email:SmtpHost");

                var userName = mailItem.Username.OrNullIfEmpty() ?? Config.GetOrThrow("Email:Username");
                var password = mailItem.Password.OrNullIfEmpty() ?? Config.GetOrThrow("Email:Password");
                smtpClient.Credentials = new NetworkCredential(userName, password);

                await Sending.Raise(new EmailSendingEventArgs(mailItem, mail));

                await smtpClient.SendMailAsync(mail);

                if (!mailItem.IsNew)
                {
                    await Entity.Database.Delete(mailItem);
                }

                await Sent.Raise(new EmailSendingEventArgs(mailItem, mail));
            }

            return(true);
        }
	    /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="message">The message.</param>
        public bool SendEmail(IEmailMessage message)
        {
            if (message == null)
            {
                return false;
            }

            var eMessage = new MailMessage();

            if (!string.IsNullOrEmpty(message.From))
            {
                eMessage.From = new MailAddress(message.From);
            }

            foreach (var to in message.To.Where(to => !string.IsNullOrEmpty(to)))
            {
                eMessage.To.Add(new MailAddress(to));
            }

            eMessage.Subject = message.Subject;

            if (!string.IsNullOrEmpty(message.Html))
            {
                eMessage.Body = message.Html;
                eMessage.IsBodyHtml = true;
            }
            else if (!string.IsNullOrEmpty(message.Text))
            {
                eMessage.Body = message.Text;
            }

            //Add attachments
            var openedStream = new List<Stream>();
            if (message.Attachments != null & message.Attachments.Count > 0)
            {
                foreach (var attachment in message.Attachments)
                {
                    try
                    {
                        var stream = new MemoryStream(attachment.Length);
                        stream.Write(attachment, 0, attachment.Length);
                        stream.Position = 0;
                        var eAttachment = new Attachment(stream, (string)null);
                        eMessage.Attachments.Add(eAttachment);
                        openedStream.Add(stream);

                    }
                    catch { return false; }
                }
            }

            var client = new SmtpClient();
            client.Send(eMessage);

            //Must close streams here otherwise client.Send will fail with exception
            openedStream.ForEach(s => s.Dispose());

            return true;
        }
Example #40
0
        public void SendEmail(IEmailMessage email)
        {
            // NOTE: http://developer.xamarin.com/recipes/android/networking/email/send_an_email/

            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                // NOTE: http://developer.android.com/guide/components/intents-common.html#Email

                string intentAction = Intent.ActionSend;
                if (email.Attachments.Count > 1)
                    intentAction = Intent.ActionSendMultiple;

                Intent emailIntent = new Intent(intentAction);
                emailIntent.SetType("message/rfc822");

                if (email.Recipients.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraEmail, email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraCc, email.RecipientsCc.ToArray());

                if (email.RecipientsBcc.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraBcc, email.RecipientsBcc.ToArray());

                emailIntent.PutExtra(Intent.ExtraSubject, email.Subject);

                // NOTE: http://stackoverflow.com/questions/13756200/send-html-email-with-gmail-4-2-1

                if (((EmailMessage)email).IsHtml)
                    emailIntent.PutExtra(Intent.ExtraText, Html.FromHtml(email.Message));
                else
                    emailIntent.PutExtra(Intent.ExtraText, email.Message);

                if (email.Attachments.Count > 0)
                {
                    var uris = new List<IParcelable>();
                    foreach (var attachment in email.Attachments)
                    {
                        var uri = Android.Net.Uri.Parse("file://" + ((EmailAttachment)attachment).FilePath);
                        uris.Add(uri);
                    }

                    if (uris.Count > 1)
                        emailIntent.PutParcelableArrayListExtra(Intent.ExtraStream, uris);
                    else
                        emailIntent.PutExtra(Intent.ExtraStream, uris[0]);
                }

                emailIntent.StartNewActivity();
            }
        }
Example #41
0
 public Plugin( 
     IEmailServer emailServer,
     IEmailMessage emailMessage,
     IStaticSettings staticSettings,
     IDisk disk)
 {
     _emailServer = emailServer ;
     _emailMessage = emailMessage ;
     _staticSettings = staticSettings ;
     _disk = disk ;
 }
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool SendEmail(IEmailMessage message)
        {
            if (message == null)
            {
                return false;
            }

            //Smtp settings ?? is it OK to read setting directly here from config?
            var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

            // Create the email object first, then add the properties.
            var eMessage = SendGrid.GetInstance();

            eMessage.From = !string.IsNullOrEmpty(message.From) ? new MailAddress(message.From) : new MailAddress(smtp.From);

            // Add multiple addresses to the To field.
            eMessage.AddTo(message.To);

            eMessage.Subject = message.Subject;

            //Add the HTML and Text bodies
            eMessage.Html = message.Html;
            eMessage.Text = message.Text;

            //Add attachments
            if (message.Attachments != null && message.Attachments.Count > 0)
            {
                foreach (var attachment in message.Attachments)
                {
                    try
                    {
                        using (var stream = new MemoryStream(attachment.Length))
                        {
                            stream.Write(attachment, 0, attachment.Length);
                            stream.Position = 0;
                            eMessage.AddAttachment(stream, "file_" + message.Attachments.IndexOf(attachment));
                        }

                    }
                    catch { return false; }
                }
            }

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential(smtp.Network.UserName, smtp.Network.Password);

            // Create an SMTP transport for sending email.
            var transportSMTP = SMTP.GetInstance(credentials, smtp.Network.Host, smtp.Network.Port);

            // Send the email.
            transportSMTP.Deliver(eMessage);

            return true;
        }
Example #43
0
		internal UsageEmailDialog()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			richTextBox2.Text = "May we ask you a favor? We would like to send a tiny e-mail back to the software developers telling us of your progress.\nYou will be able to view the e-mail before it goes out. You do not need to be connected to the Internet right now...the e-mail will just open and you can save it in your outbox.";
			m_topLineText.Text = string.Format(this.m_topLineText.Text, UsageReporter.AppNameToUseInDialogs);
			_emailProvider = EmailProviderFactory.PreferredEmailProvider();
			_emailMessage = _emailProvider.CreateMessage();

		}
		/// <summary>
		/// Sends the provided email message
		/// </summary>
		public void Send(IEmailMessage emailMessage)
		{
			if (emailMessage == null)
			{
				throw new ArgumentNullException("emailMessage");
			}

            // Fail Gracefully if SMTP Settings are not set
		    if(string.IsNullOrWhiteSpace(this.SMTPConfiguration.Host) || this.SMTPConfiguration.Port == 0)
		    {
		        return;
		    }

			var message = new MailMessage();

			// Set Sender
			message.From = new MailAddress(emailMessage.SenderAddress, emailMessage.SenderDisplayName);

			// Set Recipients
			emailMessage.ToRecipients.ForEach(x => message.To.Add(x));
			emailMessage.CcRecipients.ForEach(x => message.CC.Add(x));
			emailMessage.BccRecipients.ForEach(x => message.Bcc.Add(x));
			emailMessage.ReplyToRecipients.ForEach(x => message.ReplyToList.Add(x));

			// Set Content
			message.IsBodyHtml = emailMessage.FormatAsHtml;
			message.Body = emailMessage.BuildMessageBody();
			message.Subject = emailMessage.Subject;

			// Set Attachments
			if(emailMessage.Attachments.Count > 0)
			{
				emailMessage.Attachments.ForEach(x =>
				{
					var attachment = new Attachment(x.GetContentStream(), x.Name);
					message.Attachments.Add(attachment);
				});
			}

			// Set SMTP Settings
			var smtpClient = new SmtpClient(this.SMTPConfiguration.Host, this.SMTPConfiguration.Port);
			smtpClient.EnableSsl = this.SMTPConfiguration.EnableSSL;

			// Set Credentials
			if (!string.IsNullOrWhiteSpace(this.SMTPConfiguration.Username) || !string.IsNullOrWhiteSpace(this.SMTPConfiguration.Password))
			{
				smtpClient.UseDefaultCredentials = this.SMTPConfiguration.UseDefaultCredentials;
				smtpClient.Credentials = new NetworkCredential(this.SMTPConfiguration.Username, this.SMTPConfiguration.Password);
			}

			// Send Message
			smtpClient.Send(message);
		}
Example #45
0
		public bool SendMessage(IEmailMessage message)
		{
			string body = EscapeString(message.Body);
			string subject = EscapeString(message.Subject);
			var recipientTo = message.To;
			var toBuilder = new StringBuilder();

			for (int i = 0; i < recipientTo.Count; ++i)
			{
				if (i > 0)
				{
					toBuilder.Append(",");
				}
				toBuilder.Append(recipientTo[i]);
			}
			string commandLine;
			if (message.AttachmentFilePath.Count == 0)
			{
				commandLine = String.Format(
					FormatStringNoAttachments,
					toBuilder, subject, body
				);
			}
			else
			{
				// DG: attachments untested with xdg-email
				// review CP: throw if AttachmentFilePath.Count > 0 ?
				// review CP: throw if file not present?
				string attachments = EscapeString(String.Format(FormatStringAttachFile, message.AttachmentFilePath[0]));
				commandLine = String.Format(
					FormatStringWithAttachments,
					toBuilder, subject, attachments, body
				);
			}
			Console.WriteLine(commandLine);
			var p = new Process
			{
				StartInfo =
				{
					FileName = EmailCommand,
					Arguments = commandLine,
					UseShellExecute = true,
					ErrorDialog = true
				}
			};

			return p.Start();
			// Always return true. The false from p.Start may only indicate that the email client
			// was already open.
			// DG: This may be different with xdg-email
			//return true;
		}
        private MailMessage PopulateMailMessage(IEmailMessage email)
        {
            MailMessage message = new MailMessage();

            message.From = new MailAddress(email.From);
            message.To.Add(new MailAddress(email.To));
            message.Subject = email.Subject;
            message.Body = email.Body;
            message.Headers.Add("X-SME-AppDomain", AppDomain.CurrentDomain.FriendlyName);
            message.IsBodyHtml = email.IsHtml;

            return message;
        }
		public bool SendMessage(IEmailMessage message)
		{
			//string body = _body.Replace(System.Environment.NewLine, "%0A").Replace("\"", "%22").Replace("&", "%26");
			string body = Uri.EscapeDataString(message.Body);
			string subject = Uri.EscapeDataString(message.Subject);
			var recipientTo = message.To;
			var toBuilder = new StringBuilder();
			for (int i = 0; i < recipientTo.Count; ++i)
			{
				if (i > 0)
				{
					toBuilder.Append(",");
				}
				toBuilder.Append(recipientTo[i]);
			}
			string commandLine = "";
			if (message.AttachmentFilePath.Count == 0)
			{
				commandLine = String.Format("mailto:{0}?subject={1}&body={2}",
											toBuilder, subject, body);
			}
			else
			{
				// review CP: throw if AttachmentFilePath.Count > 0 ?
				// review CP: throw if file not present?
				string attachments = message.AttachmentFilePath[0];
				commandLine = String.Format("mailto:{0}?subject={1}&attachment={2}&body={3}",
											toBuilder, subject, attachments, body);
			}
			Console.WriteLine(commandLine);
			var p = new Process
			{
				StartInfo =
				{
					FileName = commandLine,
					UseShellExecute = true,
					ErrorDialog = true
				}
			};

			p.Start();
			// Always return true. The false from p.Start may only indicate that the email client
			// was already open.
			return true;
		}
Example #48
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                EmailComposeTask emailComposeTask = new EmailComposeTask
                                                    {
                                                        Subject = email.Subject,
                                                        Body = email.Message,
                                                        To = ToDelimitedAddress(email.Recipients),
                                                        Cc = ToDelimitedAddress(email.RecipientsCc),
                                                        Bcc = ToDelimitedAddress(email.RecipientsBcc)
                                                    };
                emailComposeTask.Show();
            }
        }
Example #49
0
        public void SendEmail(IEmailMessage email)
        {
            // NOTE: http://developer.xamarin.com/recipes/android/networking/email/send_an_email/

            if (email == null)
                throw new ArgumentNullException("email");

            if (email.Attachments.Count > 1)
                throw new NotSupportedException("Cannot send more than once attachment for Android"); 

            if (CanSendEmail)
            {
                Intent emailIntent = new Intent(Intent.ActionSend);
                emailIntent.SetType("message/rfc822");

                if (email.Recipients.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraEmail, email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraCc, email.RecipientsCc.ToArray());

                if (email.RecipientsBcc.Count > 0)
                    emailIntent.PutExtra(Intent.ExtraBcc, email.RecipientsBcc.ToArray());

                emailIntent.PutExtra(Intent.ExtraSubject, email.Subject);

                // NOTE: http://stackoverflow.com/questions/13756200/send-html-email-with-gmail-4-2-1

                if (((EmailMessage) email).IsHtml)
                    emailIntent.PutExtra(Intent.ExtraText, Html.FromHtml(email.Message));
                else
                    emailIntent.PutExtra(Intent.ExtraText, email.Message);

                if (email.Attachments.Count > 0)
                {
                    var attachment = (EmailAttachment) email.Attachments[0];
                    var uri = Android.Net.Uri.Parse("file://" + attachment.FilePath);
                    
                    emailIntent.PutExtra(Intent.ExtraStream, uri);
                }

                emailIntent.StartNewActivity();
            }
        }
Example #50
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                _mailController = new MFMailComposeViewController();
                _mailController.SetSubject(email.Subject);
                _mailController.SetMessageBody(email.Message, ((EmailMessage) email).IsHtml);
                _mailController.SetToRecipients(email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                    _mailController.SetCcRecipients(email.RecipientsCc.ToArray());

                if (email.RecipientsBcc.Count > 0)
                    _mailController.SetBccRecipients(email.RecipientsBcc.ToArray());

                foreach (var attachment in email.Attachments.Cast<EmailAttachment>())
                {
                    _mailController.AddAttachmentData(NSData.FromStream(attachment.Content),
                        attachment.ContentType, attachment.FileName);
                }

                EventHandler<MFComposeResultEventArgs> handler = null;
                handler = (sender, e) =>
                {
                    _mailController.Finished -= handler;

                    var uiViewController = sender as UIViewController;
                    if (uiViewController == null)
                    {
                        throw new ArgumentException("sender");
                    }

                    uiViewController.DismissViewController(true, () => { });
                };

                _mailController.Finished += handler;

                _mailController.PresentUsingRootViewController();
            }
        }
Example #51
0
        public virtual async Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException("emailMessage", "Supplied argument 'emailMessage' is null.");
            }

            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var email = new Windows.ApplicationModel.Email.EmailMessage()
            {

            };

 
            await EmailManager.ShowComposeNewEmailAsync(null);
        }
Example #52
0
        public virtual Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var mailer = new MFMailComposeViewController();

            mailer.SetToRecipients(emailMessage.To.ToArray());
            mailer.SetCcRecipients(emailMessage.Cc.ToArray());
            mailer.SetBccRecipients(emailMessage.Bcc.ToArray());

            mailer.SetSubject(emailMessage.Subject);
            mailer.SetMessageBody(emailMessage.Body, emailMessage.IsHTML);

            mailer.Finished += (s, e) => ((MFMailComposeViewController) s).DismissViewController(true, () => { });

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);

            return Task.FromResult(true);
        }
 public ISendEmailResult Dispatch(IEmailMessage email)
 {
     MailMessage message = PopulateMailMessage(email);
     return Dispatch(message);
 }
 public static void Send(IEmailMessage message)
 {
 }
 /// <summary>
 /// Sends an email asynchronously.
 /// </summary>
 /// <param name="emailMessage">The email message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// A Task.
 /// </returns>
 public Task SendAsync(IEmailMessage emailMessage, CancellationToken cancellationToken = default(CancellationToken))
 {
     return TaskHelper.CompletedTask;
 }
Example #56
0
        /// <summary>
        /// Sends an email asynchronously.
        /// </summary>
        /// <param name="emailMessage">The email message.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A Task.
        /// </returns>
        public Task SendAsync(IEmailMessage emailMessage, CancellationToken cancellationToken = default(CancellationToken))
        {
            var smtpClient = this.CreateSmtpClient();

            return smtpClient.SendMailAsync(emailMessage.ToMailMessage());
        }