/// <summary>
        /// Allows the user to send an email with the specified address, body and attachment - will launch the default email client
        /// </summary>
        /// <param name="to">Prepopulate the to field</param>
        /// <param name="subject">Prepopulate the subject field</param>
        /// <param name="messageBody">Prepopulate the email body</param>
        /// <param name="attachmentFilename">Filename of the attachment - optional</param>
        /// <param name="attachmentData">Data for the attachment - optional</param>
        public static void ComposeEmail(string to, string subject, string messageBody, string attachmentFilename = null, byte[] attachmentData = null)
        {
#if NETFX_CORE || (ENABLE_IL2CPP && UNITY_WSA_10_0)
            UnityEngine.WSA.Application.InvokeOnUIThread(async() =>
            {
                EmailMessage emailMessage = new EmailMessage()
                {
                    Subject = subject,
                    Body    = messageBody
                };

                if (!string.IsNullOrWhiteSpace(attachmentFilename) && attachmentData != null)
                {
                    InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();

                    await memoryStream.WriteAsync(attachmentData.AsBuffer());

                    IRandomAccessStreamReference stream = RandomAccessStreamReference.CreateFromStream(memoryStream);

                    EmailAttachment emailAttachment = new EmailAttachment(attachmentFilename, stream);

                    emailMessage.Attachments.Add(emailAttachment);
                }

                emailMessage.To.Add(new EmailRecipient(to));

                await EmailManager.ShowComposeNewEmailAsync(emailMessage);
            }, false);
#endif
        }
예제 #2
0
    static async Task MailLogFileAsync(IReadOnlyList <StorageFile> logFiles, int exceptionCount)
    {
        using (SmtpClient client = new SmtpClient("smtp.1and1.com", 587, false, "*****@*****.**", "Allatonce1.1"))
        {
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
            emailMessage.Subject = "Log Report from BreadPlayer";
            string body = "Device Family: {0}" + "\r\n" +
                          "OS Version: {1}" + "\r\n" +
                          "OS Architecture: {2}" + "\r\n" +
                          "Device Model: {3}" + "\r\n" +
                          "Device Manufacturer: {4}" + "\r\n" +
                          "App Version: {5}" + "\r\n" +
                          "Date Reported: {6}" + "\r\n" +
                          "Exception Count: {7}";
            emailMessage.Body = string.Format(body, Info.SystemFamily, Info.SystemVersion, Info.SystemArchitecture, Info.DeviceModel, Info.DeviceManufacturer, Info.ApplicationVersion, DateTime.Now, exceptionCount);
            foreach (var logFile in logFiles)
            {
                var stream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(logFile);

                var attachment = new EmailAttachment(
                    logFile.Name,
                    stream);

                emailMessage.Attachments.Add(attachment);
            }
            var x = await client.SendMailAsync(emailMessage);

            if (x == SmtpResult.OK)
            {
                await ApplicationData.Current.TemporaryFolder.DeleteAsync(StorageDeleteOption.PermanentDelete);
            }
        }
    }
예제 #3
0
        public async Task SendEmailEmptyPasswordTaskSpanishKo()
        {
            var defaultCulture = Thread.CurrentThread.CurrentUICulture;

            Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");

            var smtp = GetService <IOptionsService <SmtpSettings> >();

            smtp.Value.Password = null;
            var sender = new SmtpEmailSender(smtp);

            var bytes = await GetPhotoBinary();

            var attachment = new EmailAttachment("Adjunto", bytes);

            Task Action()
            {
                return(sender.SendEmailAsync("*****@*****.**", "Testing con adjunto",
                                             "Prueba testing con adjunto", attachment));
            }

            var exception = await Assert.ThrowsAsync <EmailException>(Action);

            //The thrown exception can be used for even more detailed assertions.
            Assert.Equal(ExceptionCodes.SMT_PASS_EMPTY, exception.Message);

            Thread.CurrentThread.CurrentUICulture = defaultCulture;
        }
    public static bool SendEmail(string mailTo, string subject, string body, EmailAttachment attachment = null, string attachmentFile = "", string mailCc = "", string mailBc = "", string mailReplyTo = "")
    {
        var smtp = new SmtpClient()
        {
            Host                  = SMTP_HOST,
            Port                  = SMTP_PORT,
            EnableSsl             = REQUIRE_SSL,
            UseDefaultCredentials = false,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            Credentials           = new System.Net.NetworkCredential(ACCOUNT_EMAIL, ACCOUNT_PASSWORD)
        };

        var mail = new MailMessage();

        mail.From = new MailAddress(ACCOUNT_EMAIL);
        string[] mailTos = mailTo.Split(MULTI_MAILTO_SEPARATOR).ToArray();
        foreach (var mailto in mailTos)
        {
            mail.To.Add(mailto);
        }
        if (!String.IsNullOrEmpty(mailCc))
        {
            mail.CC.Add(mailCc);
        }
        if (!String.IsNullOrEmpty(mailBc))
        {
            mail.Bcc.Add(mailBc);
        }
        if (!String.IsNullOrEmpty(mailReplyTo))
        {
            mail.ReplyToList.Add(mailReplyTo);
        }
        mail.Subject    = SUBJECT_LABEL + " " + subject;
        mail.IsBodyHtml = IS_HTML;
        mail.Body       = body;

        try
        {
            if (attachment != null && string.IsNullOrEmpty(attachmentFile))
            {
                using (var attachmentStream = new MemoryStream(attachment.Data))
                {
                    mail.Attachments.Add(new Attachment(attachmentStream, attachment.FileName, attachment.ContentType));
                    smtp.Send(mail);
                }
                return(true);
            }
            else if (!string.IsNullOrEmpty(attachmentFile) && attachment == null)
            {
                mail.Attachments.Add(new Attachment(attachmentFile));
            }

            smtp.Send(mail);
            return(true);
        }
        catch
        {
            return(false);
        }
    }
예제 #5
0
        protected void GeneratePDFFiles(EmailAttachment attachment, List<EmailAttachment> ListWithID)
        {

            FileSystemBL FSBL = new FileSystemBL();
            if (attachment.IsSelected)
            {
                var count = (from c in ListWithID where c.FileName == attachment.FileName select c).Count();
                if (count == 0)
                {
                    Stream receiveStream = null;
                    ELT.COMMON.Util.ReadFileStream(Url.Content(attachment.GeneratorPath), ref receiveStream);
                    if (receiveStream != null)
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            receiveStream.CopyTo(memoryStream);
                            Byte[] array = memoryStream.ToArray();
                            ELTFileSystemItem item = new ELTFileSystemItem() { Data = new Binary(array), Name = attachment.FileName + ".pdf", ParentID = -1, Owner_Email = "*****@*****.**" };

                            FSBL.InsertFile(item);
                            attachment.FileID = item.ID;
                            ListWithID.Add(attachment);
                        }
                    }
                }
            }
        }      
예제 #6
0
        public Task SendAsync(EmailMessage message, EmailAttachment attachment = null)
        {
            var mailMessage = GetMessage(message, attachment);

            _smtp.SendAsync(mailMessage, null);
            return(null);
        }
        public async Task SendAsync(ILogView log)
        {
            Copy(log);

            var message = new EmailMessage
            {
                Body    = s_resources.GetString("MessageBody"),
                Subject = string.Format(s_resources.GetString("MessageSubject"), log.Id, File.ReadAllText("version.txt").Trim())
            };

            message.To.Add(new EmailRecipient(s_resources.GetString("MessageTo"), s_resources.GetString("MessageToName")));

            using (var ms = new InMemoryRandomAccessStream())
            {
                using (var writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteString(log.Log);

                    await writer.StoreAsync();

                    await writer.FlushAsync();

                    var data = RandomAccessStreamReference.CreateFromStream(ms);

                    var attachment = new EmailAttachment($"{log.Id}.log", data);

                    message.Attachments.Add(attachment);

                    await EmailManager.ShowComposeNewEmailAsync(message);
                }
            }
        }
        private static List <EmailAttachment> GetEmailAttachmentsFromTemplate(Guid templateId,
                                                                              UserConnection userConnection)
        {
            var          result       = new List <EmailAttachment>();
            EntitySchema entitySchema = userConnection.EntitySchemaManager.GetInstanceByName("EmailTemplateFile");
            var          srcESQ       = new EntitySchemaQuery(entitySchema);

            srcESQ.IsDistinct = true;
            srcESQ.AddColumn(srcESQ.RootSchema.GetPrimaryColumnName());
            srcESQ.AddColumn("Data");
            srcESQ.Filters.Add(srcESQ.CreateFilterWithParameters(FilterComparisonType.Equal, "EmailTemplate",
                                                                 templateId));
            var fileList       = srcESQ.GetEntityCollection(userConnection);
            var fileRepository = ClassFactory.Get <FileRepository>(new ConstructorArgument("userConnection", userConnection));

            foreach (var file in fileList)
            {
                var fileId = file.PrimaryColumnValue;
                using (var memoryStream = new MemoryStream()) {
                    var bwriter    = new BinaryWriter(memoryStream);
                    var fileInfo   = fileRepository.LoadFile(entitySchema.UId, fileId, bwriter);
                    var attachment = new EmailAttachment()
                    {
                        Id        = fileId,
                        Name      = fileInfo.FileName,
                        Data      = memoryStream.ToArray(),
                        IsContent = true
                    };
                    result.Add(attachment);
                }
            }
            return(result);
        }
예제 #9
0
        public async static Task <EmailAttachment> GetLogFileAttachement()
        {
            try
            {
                var localfolder = ApplicationData.Current.LocalFolder;
                var file        = await localfolder.GetFileAsync("error.log");

                if (file == null)
                {
                    throw new ArgumentNullException();
                }

                var copiedFile = await file.CopyAsync(localfolder, "error.log", NameCollisionOption.GenerateUniqueName);

                await file.DeleteAsync(StorageDeleteOption.PermanentDelete);

                if (copiedFile == null)
                {
                    throw new ArgumentNullException();
                }

                var attachment = new EmailAttachment();
                attachment.FileName = "错误日志.log";
                attachment.Data     = RandomAccessStreamReference.CreateFromFile(copiedFile);

                return(attachment);
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #10
0
        private async void ExecuteUploadLogs(object parameter)
        {
            await Logger.Current.Flush();

            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            StorageFolder logFolder = await localFolder.GetFolderAsync(Logger.LOG_FOLDER);

            if (logFolder == null)
            {
                return;
            }

            IReadOnlyList <StorageFile> files = await logFolder.GetFilesAsync();

            EmailRecipient sendTo = new EmailRecipient(EMAIL_TARGET, EMAIL_NAME);

            EmailMessage mail = new EmailMessage();

            mail.Subject = Strings.GetResource("SendLogsSubject");
            mail.Body    = Strings.GetResource("SendLogsBody");

            mail.To.Add(sendTo);

            foreach (IStorageFile file in files)
            {
                EmailAttachment logs = new EmailAttachment(file.Name, file);

                mail.Attachments.Add(logs);
            }

            await EmailManager.ShowComposeNewEmailAsync(mail);
        }
예제 #11
0
        public async Task <IActionResult> SendEmailAttachments()
        {
            var user = new User
            {
                Email       = "*****@*****.**",
                DisplayName = "John Doe"
            };

            var context = new
            {
                ApplicationName = "Email Sender Sample",
                User            = user
            };

            var data  = System.IO.File.ReadAllBytes(@"Files\beach.jpeg");
            var image = new EmailAttachment("Beach.jpeg", data, "image", "jpeg");

            data = System.IO.File.ReadAllBytes(@"Files\sample.pdf");
            var pdf = new EmailAttachment("Sample.pdf", data, "application", "pdf");

            await this.emailSender.SendTemplatedEmailAsync(
                new EmailAddress("*****@*****.**", "Sender"),
                "Invitation",
                context,
                new List <IEmailAttachment> {
                image, pdf
            },
                user);

            return(RedirectToAction("Index"));
        }
        public async void TestDocumentAttachments()
        {
            var configManager    = new ServiceDbConfigManager("TestService");
            var dbAccess         = CreateDbAccess(configManager);
            var dbAccessProvider = new TestDocumentDbAccessProvider(dbAccess);

            var store = new EmailStore(dbAccessProvider);

            await dbAccess.Open(new[] { store });

            var email = new Email
            {
                Id      = Guid.NewGuid(),
                Subject = "Re: Holiday"
            };

            var attachment = new EmailAttachment
            {
                Data = "test"
            };

            // Store without attachment.
            await store.Upsert(email, null);

            var actualAttachment = await store.GetEmailAttachment(email.Id);

            Assert.Null(actualAttachment);

            // Store with attachment.
            await store.Upsert(email, attachment);

            actualAttachment = await store.GetEmailAttachment(email.Id);

            Assert.Equal(attachment.Data, actualAttachment.Data);
        }
        /// <summary>
        /// Email the zipped log files.
        /// </summary>
        private async void HandleEmailButtonClick(object sender, RoutedEventArgs e)
        {
            Log.Info("LogFilesPage.HandleEmailButtonClick");
            EmailMessage message = new EmailMessage();

            message.To.Add(new EmailRecipient("*****@*****.**"));
            message.Subject = Res.Str.AppName + " " + Res.Str.LogFiles;
            StorageFile zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync("LogFiles.zip");

            if (zipFile != null)
            {
                await zipFile.DeleteAsync();
            }
            string fileName = Path.Combine(ApplicationData.Current.LocalFolder.Path, "LogFiles.zip");

            message.Body = string.Format(Res.Str.AttachmentWarning, fileName);
            ZipFile.CreateFromDirectory(Log.Folder.Path, fileName, CompressionLevel.Optimal, true);
            zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync("LogFiles.zip");

            if (zipFile != null)
            {
                var stream     = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(zipFile);
                var attachment = new EmailAttachment(zipFile.Name, stream);
                message.Attachments.Add(attachment);
                await EmailManager.ShowComposeNewEmailAsync(message);
            }
            else
            {
                Utils.ErrorAsync(Res.Error.CouldntCreateZipFile);
            }
        }
예제 #14
0
        /// <summary>
        /// Replaces Base64 strings with cid in e-mail content.
        /// </summary>
        /// <param name="htmlBody">E-mail html content.</param>
        /// <param name="attachments">Collection of items of <see cref="Sender.EmailAttachment"/> type.</param>
        /// <param name="contentIds">Collection of content items identifiers.</param>
        /// <returns>Html content.</returns>
        private string ReplaceBase64ImgSrc(string htmlBody, ICollection <EmailAttachment> attachments,
                                           ICollection <Guid> contentIds)
        {
            string matchPattern = @"(?<=<\s*img.+?src[^""]+?"")(?<mimeType>[^,""]+,)(?<base64>(?:[\w+/]+)[\w+/]{2}[\w+/=]=)";

            foreach (Match match in Regex.Matches(htmlBody, matchPattern))
            {
                string mimeType    = match.Groups["mimeType"].Value;
                string base64Image = match.Groups["base64"].Value;
                Guid   id          = Guid.NewGuid();
                string fileName    = GetBase64FileName(id, mimeType);
                var    attachment  = new EmailAttachment {
                    Id        = id,
                    Name      = fileName,
                    Data      = Convert.FromBase64String(base64Image),
                    IsContent = true
                };
                attachments.Add(attachment);
                contentIds.Add(id);
                string attachmentCid  = string.Format("cid:{0}", id);
                var    replacePattern = new Regex(Regex.Escape(string.Concat(mimeType, base64Image)));
                htmlBody = replacePattern.Replace(htmlBody, attachmentCid, 1);
            }
            return(htmlBody);
        }
예제 #15
0
        public async Task SendWithAttachments()
        {
            var options = Datas.GetOptions(storeFixture);

            var providerTypes = new List <IEmailProviderType>
            {
                new SendGrid.SendGridEmailProviderType(),
            };

            var emailSender = new Internal.EmailSender(
                providerTypes,
                options,
                this.storeFixture.Services.GetRequiredService <IStorageFactory>(),
                this.storeFixture.Services.GetRequiredService <ITemplateLoaderFactory>());

            var data  = System.IO.File.ReadAllBytes(@"Files\beach.jpeg");
            var image = new EmailAttachment("Beach.jpeg", data, "image", "jpeg");

            data = System.IO.File.ReadAllBytes(@"Files\sample.pdf");
            var pdf = new EmailAttachment("Sample.pdf", data, "application", "pdf");

            await emailSender.SendEmailAsync(new Internal.EmailAddress
            {
                DisplayName = "test user attachm ments",
                Email       = "*****@*****.**"
            }, "Test mail with attachments", "Hello, this is an email with attachments", new List <IEmailAttachment> {
                image, pdf
            }, new Internal.EmailAddress
            {
                DisplayName = "test user",
                Email       = Datas.FirstRecipient
            });
        }
예제 #16
0
        /// <summary>
        /// Returns list of <see cref="EmailAttachment"/> items.
        /// </summary>
        /// <param name="esq">Instance of <see cref="EntitySchemaQuery"/> type.</param>
        /// <returns>List of attachments.</returns>
        protected List <EmailAttachment> GetEmailAttachments(EntitySchemaQuery esq)
        {
            EntitySchemaQueryColumn idColumn     = esq.AddColumn("Id");
            EntityCollection        fileEntities = esq.GetEntityCollection(UserConnection);
            var attachments    = new List <EmailAttachment>();
            var fileRepository = ClassFactory.Get <FileRepository>(
                new ConstructorArgument("userConnection", UserConnection));

            foreach (Entity fileEntity in fileEntities)
            {
                Guid id = fileEntity.GetTypedColumnValue <Guid>(idColumn.Name);
                using (var memoryStream = new MemoryStream()) {
                    var    bwriter  = new BinaryWriter(memoryStream);
                    var    fileInfo = fileRepository.LoadFile(esq.RootSchema.UId, id, bwriter);
                    string fileName = CheckInvalidFileName(fileInfo.FileName)
                                                ? fileInfo.FileName
                                                : Path.GetFileName(fileInfo.FileName);
                    var attachment = new EmailAttachment {
                        Id        = id,
                        Name      = fileName,
                        Data      = memoryStream.ToArray(),
                        IsContent = false
                    };
                    attachments.Add(attachment);
                }
            }
            return(attachments);
        }
        private async void ReportButton_Click(object sender, RoutedEventArgs e)
        {
            var rec = new EmailRecipient("*****@*****.**");
            var mes = new EmailMessage();

            mes.To.Add(rec);

            var result = "";

            foreach (var l in _paragraph.Inlines)
            {
                if (l is Run)
                {
                    result += (l as Run).Text;
                }
            }

            var cachedFolder = ApplicationData.Current.TemporaryFolder;
            var file         = await cachedFolder.CreateFileAsync("network_diagnosis.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(file, result);

            var stream     = RandomAccessStreamReference.CreateFromFile(file);
            var attachment = new EmailAttachment(file.Name, stream);

            mes.Attachments.Add(attachment);
            mes.Subject = $"【Network】MyerSplash for Windows 10, {App.GetAppVersion()} feedback, {DeviceHelper.OSVersion}";
            mes.Body    = ResourceLoader.GetForCurrentView().GetString("EmailBody");
            await EmailManager.ShowComposeNewEmailAsync(mes);
        }
예제 #18
0
        public async Task SendEmail()
        {
            var model = new EmployeeEmailModel();

            model.EmployeeName = "Test Employee";

            model.ToList.Add("*****@*****.**");
            model.ToList.Add("*****@*****.**");

            model.CCList.Add("*****@*****.**");
            model.CCList.Add("*****@*****.**");

            model.BCCList.Add("*****@*****.**");
            model.BCCList.Add("*****@*****.**");

            model.Subject     = "Testing Email";
            model.FromAddress = "*****@*****.**";

            var emailAttachment = new EmailAttachment();
            var streams         = new List <System.IO.MemoryStream>();

            emailAttachment.Filename    = "Holiday-calendar2018_KGS.pdf";
            emailAttachment.ContentType = "application/pdf";
            var filename = "C:\\Test\\Holiday-calendar2018_KGS.pdf";

            byte[] bytes = System.IO.File.ReadAllBytes(filename);
            emailAttachment.FileContents = bytes;

            await _emailService.QueueEmail((BaseEmailViewModel)model, new List <EmailAttachment>() { emailAttachment });

            await _emailService.SendEmail();
        }
예제 #19
0
        public static async Task AddAttachment(EmailMessage email, string filename, string name)
        {
            try
            {
                StorageFile attachmentFileCopy = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);

                BasicProperties properties = await attachmentFileCopy.GetBasicPropertiesAsync();

                if (properties.Size > 0)
                {
                    await attachmentFileCopy.CopyAsync(ApplicationData.Current.LocalFolder, filename + ".bak", NameCollisionOption.ReplaceExisting);

                    StorageFile attachmentFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename + ".bak");

                    if (attachmentFile != null)
                    {
                        var stream     = RandomAccessStreamReference.CreateFromFile(attachmentFile);
                        var attachment = new EmailAttachment(name, stream);
                        email.Attachments.Add(attachment);
                    }
                }
            }
            catch (Exception ex)
            {
                TrackingManagerHelper.Exception(ex, "Adding attachment");
            }
        }
예제 #20
0
        public List <EmailAttachment> AddAttachments(IFormFile[] files, Guid id, string driveName)
        {
            if (driveName != "Files" && !string.IsNullOrEmpty(driveName))
            {
                throw new EntityOperationException("Component files can only be saved in the Files drive");
            }
            else if (string.IsNullOrEmpty(driveName))
            {
                driveName = "Files";
            }

            var attachments = new List <EmailAttachment>();

            if (files?.Length != 0 && files != null)
            {
                //add files to drive
                string storagePath = Path.Combine(driveName, "Email Attachments", id.ToString());
                var    fileView    = new FileFolderViewModel()
                {
                    StoragePath     = storagePath,
                    FullStoragePath = storagePath,
                    Files           = files,
                    IsFile          = true
                };

                long?size = 0;
                foreach (var file in files)
                {
                    size += file.Length;
                }

                CheckStoragePathExists(fileView, size, id, driveName);
                var fileViewList = _fileManager.AddFileFolder(fileView, driveName);

                foreach (var file in fileViewList)
                {
                    //create email attachment
                    EmailAttachment emailAttachment = new EmailAttachment()
                    {
                        Name                  = file.Name,
                        FileId                = file.Id,
                        ContentType           = file.ContentType,
                        ContentStorageAddress = file.FullStoragePath,
                        SizeInBytes           = file.Size,
                        EmailId               = id,
                        CreatedOn             = DateTime.UtcNow,
                        CreatedBy             = _httpContextAccessor.HttpContext.User.Identity.Name
                    };
                    _emailAttachmentRepository.Add(emailAttachment);
                    attachments.Add(emailAttachment);
                }
            }
            else
            {
                throw new EntityOperationException("No files found to attach");
            }

            return(attachments);
        }
예제 #21
0
        public static void Constructor_InitializesFileName()
        {
            const string fileName = "file.pdf";

            var attachment = new EmailAttachment(fileName, Mock.Of <Stream>());

            attachment.FileName.Should().Be(fileName);
        }
예제 #22
0
        public static void Constructor_InitializesContent()
        {
            var content = Mock.Of <Stream>();

            var attachment = new EmailAttachment("fileName", content);

            attachment.Content.Should().BeSameAs(content);
        }
        private void SaveAttachment(int emailId, EmailAttachment newAttachment)
        {
            EmailAttachmentTableAdapter adapter = new EmailAttachmentTableAdapter();
            int?id = 0;

            adapter.Insert(emailId, newAttachment.Name, newAttachment.Path, ref id);
            newAttachment.Id = (int)id;
        }
예제 #24
0
 public static EmailSenderViaQueueContract.EmailAttachmentContract ToContract(this EmailAttachment src)
 {
     return(new EmailSenderViaQueueContract.EmailAttachmentContract
     {
         Mime = src.Mime,
         FileName = src.FileName,
         Data = src.Data.ToBase64()
     });
 }
예제 #25
0
        /// <summary>
        /// Send a email with attached files.
        /// </summary>
        /// <param name="recipient"></param>
        /// <param name="subject"></param>
        /// <param name="attachment"></param>
        /// <returns></returns>
        public async Task Send(string recipient, string subject, EmailAttachment attachment)
        {
            var email = new EmailMessage();
            email.To.Add(new EmailRecipient(recipient));
            email.Subject = subject;
            email.Attachments.Add(attachment);

            await EmailManager.ShowComposeNewEmailAsync(email);
        }
            public async Task Upsert(Email doc, EmailAttachment attachment)
            {
                var upsertResult = await StoreClient.UpsertDocumentAsync(doc, _mapping, null);

                if (attachment != null)
                {
                    await StoreClient.CreateAttachmentAsync(doc, upsertResult.DocumentVersion, _attachmentMapping, attachment);
                }
            }
예제 #27
0
 public SendEmail(string destinationAddress,
                  string senderName,
                  string senderEmail,
                  string subject,
                  EmailTemplate templateType,
                  EmailAttachment attachment) : this(destinationAddress, senderName, senderEmail, subject, templateType)
 {
     Attachment = attachment;
 }
예제 #28
0
 public static EmailRabbitMqAttachmentContract Create(EmailAttachment src)
 {
     return(new EmailRabbitMqAttachmentContract
     {
         FileName = src.FileName,
         Data = Convert.ToBase64String(src.Data),
         Mime = src.Mime
     });
 }
예제 #29
0
        public List <EmailAttachment> AddAttachments(IFormFile[] files, Guid id, string driveId)
        {
            driveId = CheckDriveId(driveId);
            var drive = GetDrive(driveId);

            driveId = drive.Id.ToString();

            var attachments = new List <EmailAttachment>();

            if (files?.Length != 0 && files != null)
            {
                //add files to drive
                string storagePath = Path.Combine(drive.Name, "Email Attachments", id.ToString());
                var    fileView    = new FileFolderViewModel()
                {
                    StoragePath     = storagePath,
                    FullStoragePath = storagePath,
                    Files           = files,
                    IsFile          = true
                };

                long?size = 0;
                foreach (var file in files)
                {
                    size += file.Length;
                }

                CheckStoragePathExists(fileView, size, id, driveId, drive.Name);
                var fileViewList = _fileManager.AddFileFolder(fileView, driveId);

                foreach (var file in fileViewList)
                {
                    string[] fileNameArray = file.Name.Split(".");
                    string   extension     = fileNameArray[1];
                    //create email attachment
                    EmailAttachment emailAttachment = new EmailAttachment()
                    {
                        Name                  = file.Name,
                        FileId                = file.Id,
                        ContentType           = file.ContentType,
                        ContentStorageAddress = Path.Combine(drive.OrganizationId.ToString(), drive.Id.ToString(), $"{file.Id}.{extension}"),
                        SizeInBytes           = file.Size,
                        EmailId               = id,
                        CreatedOn             = DateTime.UtcNow,
                        CreatedBy             = _httpContextAccessor.HttpContext.User.Identity.Name
                    };
                    _emailAttachmentRepository.Add(emailAttachment);
                    attachments.Add(emailAttachment);
                }
            }
            else
            {
                throw new EntityOperationException("No files found to attach");
            }

            return(attachments);
        }
예제 #30
0
        public void InsertEmailAttachment(EmailAttachment emailAttachment)
        {
            if (emailAttachment == null)
            {
                throw new ArgumentNullException("emailAttachment");
            }

            _emailAttachmentRepository.Insert(emailAttachment);
        }
예제 #31
0
        public virtual EmailBuilder Attach(EmailAttachment attachment)
        {
            if (attachment == null)
            {
                throw new ArgumentNullException(nameof(attachment));
            }

            Message.Attachments.Add(attachment);
            return(this);
        }
예제 #32
0
 public async void Send(string email, string subject, string body, params StorageFile[] file)
 {
     var message = new EmailMessage()
     {
         Body = body,
         Subject = subject,
     };
     message.To.Add(new EmailRecipient(email));
     file?.ForEach(f =>
     {
         var stream = RandomAccessStreamReference.CreateFromFile(f);
         var attachment = new EmailAttachment(f.Name, stream);
         message.Attachments.Add(attachment);
     });
     await EmailManager.ShowComposeNewEmailAsync(message);
 }
예제 #33
0
        public async static Task<EmailAttachment> GetLogFileAttachement()
        {
            try
            {
                var localfolder = ApplicationData.Current.LocalFolder;
                var file = await localfolder.GetFileAsync("error.log");

                if (file == null) throw new ArgumentNullException();

                var attachment = new EmailAttachment();
                attachment.FileName = "error.txt";
                attachment.Data = RandomAccessStreamReference.CreateFromFile(file);

                return attachment;
            }
            catch (Exception)
            {
                return null;
            }
        }
        private async Task HandleMessageUnprotected(MessageBase message)
        {
            this.Log("R: " + message._Source + "\r\n");

            try
            {
                if (message.Service != "SYSTEM")
                {
                    var dictionary = new Dictionary<string, string> { { "Type", message.Service } };
                    App.Telemetry.TrackEvent("MessageInfo", dictionary);
                }
            }
            catch (Exception)
            {
                // ignore telemetry errors if any
            }

            switch (message.Service)
            {
                case "SYSTEM":
                    {
                        if (message.Action.Equals("PONG"))
                        {
                            var totalRoundTrip = this.recentStringReceivedTick - this.sentPingTick;
                            App.Telemetry.TrackMetric(
                                "VirtualShieldPingPongTimeDifferenceMillisec", 
                                totalRoundTrip / TimeSpan.TicksPerMillisecond);
                        }
                        else if (message.Action.Equals("START"))
                        {
                            // reset orientation
                            DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;

                            // turn off all sensors, accept buffer length
                            var switches = new SensorSwitches { A = 0, G = 0, L = 0, M = 0, P = 0, Q = 0 };
                            var sensors = new List<SensorSwitches>();
                            sensors.Add(switches);

                            this.ToggleSensors(new SensorMessage { Sensors = sensors, Id = 0 });
                        }

                        break;
                    }

                case "SMS":
                    {
                        var smsService = new Sms();
                        var sms = message as SmsMessage;

                        StorageFile attachment = null;
                        if (!string.IsNullOrWhiteSpace(sms.Attachment))
                        {
                            attachment = await StorageFile.GetFileFromPathAsync(sms.Attachment);
                        }

                        smsService.Send(sms.To, sms.Message, attachment, null);
                        break;
                    }

                case "EMAIL":
                    {
                        var email = new EmailMessage();
                        var emailMessage = message as Core.Models.EmailMessage;
                        email.Body = emailMessage.Message;
                        email.Subject = emailMessage.Subject;
                        email.To.Add(new EmailRecipient(emailMessage.To));
                        if (!string.IsNullOrWhiteSpace(emailMessage.Cc))
                        {
                            email.CC.Add(new EmailRecipient(emailMessage.To));
                        }

                        if (!string.IsNullOrWhiteSpace(emailMessage.Attachment))
                        {
                            var storageFile = await StorageFile.GetFileFromPathAsync(emailMessage.Attachment);
                            var stream = RandomAccessStreamReference.CreateFromFile(storageFile);

                            var attachment = new EmailAttachment(storageFile.Name, stream);

                            email.Attachments.Add(attachment);
                        }

                        await EmailManager.ShowComposeNewEmailAsync(email);

                        break;
                    }

                case "NOTIFY":
                    {
                        var notify = message as NotifyMessage;
                        if (string.IsNullOrWhiteSpace(notify.Action))
                        {
                            return;
                        }

                        if (notify.Action.ToUpperInvariant().Equals("TOAST"))
                        {
                            await this.SendToastNotification(notify);
                        }
                        else if (notify.Action.ToUpperInvariant().Equals("TILE"))
                        {
                            await this.SendTileNotification(notify);
                        }

                        break;
                    }

                case "LCDG":
                case "LCDT":
                    {
                        await
                            this.dispatcher.RunAsync(
                                CoreDispatcherPriority.Normal, 
                                () => { this.screen.LcdPrint(message as ScreenMessage); });
                        break;
                    }

                case "LOG":
                    {
                        await this.screen.LogPrint(message as ScreenMessage);
                        break;
                    }

                case "SPEECH":
                    {
                        this.Speak(message as SpeechMessage);
                        break;
                    }

                case "RECOGNIZE":
                    {
                        this.Recognize(message as SpeechRecognitionMessage);
                        break;
                    }

                case "SENSORS":
                    {
                        this.ToggleSensors(message as SensorMessage);
                        break;
                    }

                case "WEB":
                    {
                        await this.web.RequestUrl(message as WebMessage);
                        break;
                    }

                case "CAMERA":
                    {
                        var camMsg = message as CameraMessage;
                        if (camMsg.Action != null && camMsg.Message != null && camMsg.Message.Equals("PREVIEW"))
                        {
                            if (camMsg.Action.Equals("ENABLE") && !this.isCameraInitialized)
                            {
                                await this.InitializeCamera();
                                this.camera.isPreviewing = true;
                            }
                            else if (camMsg.Action.Equals("DISABLE"))
                            {
                                this.camera.isPreviewing = false;
                            }
                        }
                        else
                        {
                            await this.TakePicture(message as CameraMessage);
                        }

                        break;
                    }

                case "VIBRATE":
                    {
                        this.Vibrate(message as TimingMessage);
                        break;
                    }

                case "MICROPHONE":
                    {
                        await this.Record(message as TimingMessage);
                        break;
                    }

                case "PLAY":
                    {
                        await this.Play(message as TimingMessage);
                        break;
                    }

                case "DEVICE":
                    {
                        await this.DeviceInfo(message as DeviceMessage);
                        break;
                    }
            }
        }
예제 #35
0
 public void AddToEmailAttachments(EmailAttachment emailAttachment)
 {
     base.AddObject("EmailAttachments", emailAttachment);
 }
예제 #36
0
 public static EmailAttachment CreateEmailAttachment(int attachmentID, int mailID, int contentLength)
 {
     EmailAttachment emailAttachment = new EmailAttachment();
     emailAttachment.AttachmentID = attachmentID;
     emailAttachment.MailID = mailID;
     emailAttachment.ContentLength = contentLength;
     return emailAttachment;
 }
예제 #37
0
 private async void SendMail(StorageFile file)
 {
     EmailAttachment emailAttachment = new EmailAttachment(file.Name, file);
     EmailMessage mail = new EmailMessage();
     mail.Attachments.Add(emailAttachment);
     mail.Subject = "明信片";
     mail.Body = "-------发自背包的明信片";
     await EmailManager.ShowComposeNewEmailAsync(mail);
 }
예제 #38
0
        public async static Task<EmailAttachment> GetLogFileAttachement()
        {
            try
            {
                var localfolder = ApplicationData.Current.LocalFolder;
                var file = await localfolder.GetFileAsync("error.log");

                if (file == null) throw new ArgumentNullException();

                var copiedFile = await file.CopyAsync(localfolder, "error.log", NameCollisionOption.GenerateUniqueName);
                await file.DeleteAsync(StorageDeleteOption.PermanentDelete);

                if (copiedFile == null) throw new ArgumentNullException();

                var attachment = new EmailAttachment();
                attachment.FileName = "错误日志.log";
                attachment.Data = RandomAccessStreamReference.CreateFromFile(copiedFile);

                return attachment;
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #39
0
		public static async Task SendEmailWithLogsAsync(string recipient, string appName)
		{
			EmailRecipient emailRecipient = new EmailRecipient(recipient);

			EmailMessage emailMsg = new EmailMessage { Subject = string.Format("Feedback from {0} with logs", appName) };
			emailMsg.To.Add(emailRecipient);
			//emailMsg.Body = await ReadAllLogsIntoStringAsync(); // LOLLO this only works with a short body...

			string body = await ReadAllLogsIntoStringAsync();

			using (var ms = new InMemoryRandomAccessStream())
			{
				using (var s4w = ms.AsStreamForWrite())
				{
					using (var sw = new StreamWriter(s4w, Encoding.UTF8))
					{
						await sw.WriteAsync(body);
						await sw.FlushAsync();

						// LOLLO NOTE the emails are broken with Outlook, they work with the mail app tho
						// https://msdn.microsoft.com/en-us/library/windows/apps/xaml/mt269391.aspx
						// the following brings up a preview with only the beginning of the body, at least with Outlook.
						// it truncates the body if it is too long, like with mailto:
						// emailMsg.SetBodyStream(EmailMessageBodyKind.PlainText, RandomAccessStreamReference.CreateFromStream(ms0));

						// the following instead does not work at all, at least with Outlook: no attachments are attached; the email app works fine
						emailMsg.Body = "I have attached the logs";

						ms.Seek(0);
						var att = new EmailAttachment("Logs.txt", RandomAccessStreamReference.CreateFromStream(ms)); //, "text/plain");
						emailMsg.Attachments.Add(att);

						//await s4w.FlushAsync();
						//await ms.FlushAsync();

						emailMsg.Attachments[0].EstimatedDownloadSizeInBytes = ms.Size;

						await EmailManager.ShowComposeNewEmailAsync(emailMsg); //.AsTask().ConfigureAwait(false);
					}
				}
			}
		}
예제 #40
0
 public async Task SendEmailCommandDelegate()
 {
     var attachment = new EmailAttachment("file", await CreateFile());
     await _emailService.Send("*****@*****.**", "Ejemplo envio email con adjuntos", attachment);
 }
예제 #41
0
        private static void WriteInsertAttachmentSql(TextWriter writer, EmailAttachment attachment, string messageID, int index)
        {
            InsertSqlClauseBuilder builder = ORMapping.GetInsertSqlClauseBuilder(attachment);

            builder.AppendItem("MESSAGE_ID", messageID);
            builder.AppendItem("SORT_ID", index);

            string sql = string.Format("INSERT INTO MSG.EMAIL_ATTACHMENTS{0}",
                builder.ToSqlString(TSqlBuilder.Instance));

            writer.WriteLine(sql);
        }
        /// <summary>
        /// Send an e-mail.
        /// </summary>
        /// <param name="subject">Subject of the message</param>
        /// <param name="body">Body of the message</param>
        /// <param name="toRecipients">To recipients</param>
        /// <param name="ccRecipients">CC recipients</param>
        /// <param name="bccRecipients">BCC recipients</param>
        /// <param name="attachments">File attachments to the message.</param>
        /// <returns>Awaitable task is returned.</returns>
        public async Task SendEmailAsync(string subject, string body, string[] toRecipients, string[] ccRecipients, string[] bccRecipients, params IStorageFile[] attachments)
        {
            if (toRecipients == null || toRecipients.Length == 0)
                throw new ArgumentNullException(nameof(toRecipients));

            Platform.Current.Analytics.Event("SendEmail");
            var msg = new EmailMessage();

            if (toRecipients != null)
                foreach (var address in toRecipients)
                    msg.To.Add(new EmailRecipient(address));

            if (ccRecipients != null)
                foreach (var address in ccRecipients)
                    msg.CC.Add(new EmailRecipient(address));

            if (bccRecipients != null)
                foreach (var address in bccRecipients)
                    msg.Bcc.Add(new EmailRecipient(address));

            msg.Subject = subject;
            msg.Body = body;

            if(attachments != null)
            {
                foreach(IStorageFile file in attachments)
                {
                    var stream = global::Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(file);
                    var ea = new EmailAttachment(file.Name, stream);
                    msg.Attachments.Add(ea);
                }
            }
            
            await EmailManager.ShowComposeNewEmailAsync(msg);
        }