コード例 #1
0
            public void GetsExpectedBody(EmailFormat format)
            {
                var result = Builder.GetBody(format);

                var intro = AreCredentialsExpired
                    ? $"We wanted to inform you that the following API key(s) on {Brand} have expired:"
                    : $"We wanted to inform you that the following API key(s) on {Brand} will expire soon:";

                Assert.Contains(
                    intro,
                    result);

                var visitStatement = AreCredentialsExpired
                    ? $"Visit {Url} to generate a new API key(s) so that you can continue pushing packages."
                    : $"Visit {Url} to generate a new API key(s) so that you can continue pushing packages using them.";

                Assert.Contains(
                    visitStatement,
                    result);

                foreach (var credential in new ExpiredCredentialData[] { FirstCredential, SecondCredential })
                {
                    var credentialMessage = AreCredentialsExpired
                        ? $"{credential.Description} - has expired."
                        : $"{credential.Description} - expires in {(int)(credential.Expires - JobRunTime).TotalDays} day(s).";

                    Assert.Contains(
                        credentialMessage,
                        result);
                }
            }
コード例 #2
0
        private string GetBodyInternal(EmailFormat format)
        {
            var markdown = $@"_User {FromAddress.DisplayName} <{FromAddress.Address}> sends the following message to the owners of Package '[{Package.PackageRegistration.Id} {Package.Version}]({PackageUrl})'._

{HtmlEncodedMessage}";

            string body;

            switch (format)
            {
            case EmailFormat.PlainText:
                body = ToPlainText(markdown);
                break;

            case EmailFormat.Markdown:
                body = markdown;
                break;

            case EmailFormat.Html:
                body = Markdown.ToHtml(markdown);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(format));
            }

            return(body + EmailMessageFooter.ForContactOwnerNotifications(format, _configuration.GalleryOwner.DisplayName, EmailSettingsUrl));
        }
コード例 #3
0
        public void CheckIfMailBodyDetailsIsValid()
        {
            var emailFormat = new EmailFormat("abc", "99999999", "*****@*****.**", "Illllkslk");
            var obj         = new EmailNotifier();

            Assert.False(obj.GetMailMessage(emailFormat) == null);
        }
コード例 #4
0
 private void SetEmailFormat(EmailFormat selectedEmailFormat)
 {
     // Setup the email settings
     EmailFormat[] availableValues;
     if (EmailConfigHelper.HasMAPI())
     {
         checkbox_email.Enabled       = true;
         combobox_emailformat.Visible = true;
         if (EmailConfigHelper.HasOutlook())
         {
             availableValues = new EmailFormat[] { EmailFormat.MAPI, EmailFormat.OUTLOOK_TXT, EmailFormat.OUTLOOK_HTML };
         }
         else
         {
             // Force MAPI in configuration if no Outlook
             coreConfiguration.OutputEMailFormat = EmailFormat.MAPI;
             availableValues = new EmailFormat[] { EmailFormat.MAPI };
         }
         PopulateComboBox <EmailFormat>(combobox_emailformat, availableValues, selectedEmailFormat);
     }
     else
     {
         checkbox_email.Enabled       = false;
         checkbox_email.Checked       = false;
         combobox_emailformat.Visible = false;
     }
 }
コード例 #5
0
        public void WhenNoAuthenticationIsProvidedThrowError()
        {
            var obj         = new EmailNotifier();
            var emailFormat = new EmailFormat("abc", "99999999", "*****@*****.**", "Illllkslk");

            Assert.Throws <SmtpException>(() => obj.SendCustomerInterestDetailsToMarketingTeam(emailFormat));
        }
コード例 #6
0
ファイル: EmailHelper.cs プロジェクト: ParamaBiswas/Hnm
        public EmailFormat GetEmailFormat(int emailID)
        {
            EmailFormat   objEmailFormat = new EmailFormat();
            string        vComTxt        = @"SELECT  [EmailCode]
                                      ,[EmailID]
                                      ,[EmailSubject]
                                      ,[EmailBody]
                                  FROM  [General_EmailFormat]
                                  WHERE [EmailID]= '" + emailID + "'";
            SqlConnection connection     = _supplierDbContext.GetConn();

            connection.Open();
            SqlDataReader dr;
            SqlCommand    objDbCommand = new SqlCommand(vComTxt, connection);

            dr = objDbCommand.ExecuteReader();
            if (dr.Read())
            {
                objEmailFormat = new EmailFormat();
                objEmailFormat.EmailCode_PK = dr["EmailCode"].ToString();
                objEmailFormat.EmailID      = Convert.ToInt16(dr["EmailID"].ToString());
                objEmailFormat.EmailSubject = dr["EmailSubject"].ToString();
                objEmailFormat.EmailBody    = dr["EmailBody"].ToString();
            }
            dr.Close();
            connection.Close();
            return(objEmailFormat);
        }
コード例 #7
0
        private static string ForReason(EmailFormat format, string galleryOwnerDisplayName, string emailSettingsUrl, string reason)
        {
            switch (format)
            {
            case EmailFormat.PlainText:
                // Hyperlinks within an HTML emphasis tag are not supported by the Plain Text renderer in Markdig.
                return($@"

-----------------------------------------------
    {reason}, sign in to the {galleryOwnerDisplayName} and
    change your email notification settings ({emailSettingsUrl}).");

            case EmailFormat.Html:
                // Hyperlinks within an HTML emphasis tag are not supported by the HTML renderer in Markdig.
                return($@"<hr />
<em style=""font-size: 0.8em;"">
    {reason}, sign in to the {galleryOwnerDisplayName} and
    <a href=""{emailSettingsUrl}"">change your email notification settings</a>.
</em>");

            case EmailFormat.Markdown:
                return($@"

-----------------------------------------------
<em style=""font-size: 0.8em;"">
    {reason}, sign in to the {galleryOwnerDisplayName} and
    [change your email notification settings]({emailSettingsUrl}).
</em>");

            default:
                throw new ArgumentOutOfRangeException(nameof(format));
            }
        }
 public string GetBody(EmailFormat format)
 {
     // We only create an HTML version of the body for now.
     // Ideally we would create a plaintext fallback as well, and return a different version of the body based on the format.
     // For now, however, returning an HTML body as the plaintext fallback is better than having a completely empty plaintext fallback.
     return(_htmlBody);
 }
コード例 #9
0
 /// <summary>
 /// This method will be called after reading the configuration, so eventually some corrections can be made
 /// </summary>
 public override void AfterLoad()
 {
    if (OutputDestinations == null)
    {
       OutputDestinations = new List<Destination>();
    }
    // Make sure there is an output!
    if (OutputDestinations.Count == 0)
    {
       OutputDestinations.Add(Destination.Editor);
    }
    // Check for Outlook, if it's not installed force email format to MAPI
    if (OutputEMailFormat != EmailFormat.MAPI && !EmailConfigHelper.HasOutlook())
    {
       OutputEMailFormat = EmailFormat.MAPI;
    }
    // Prevent both settings at once, bug #3435056
    if (OutputDestinations.Contains(Destination.Clipboard) && OutputFileCopyPathToClipboard)
    {
       OutputFileCopyPathToClipboard = false;
    }
    if (AutoCropDifference < 0)
    {
       AutoCropDifference = 0;
    }
    if (AutoCropDifference > 255)
    {
       AutoCropDifference = 255;
    }
 }
コード例 #10
0
            public void ReturnsExpectedBodyForNonApiKey(EmailFormat format, string expectedString)
            {
                var message = CreateMessage(Fakes.NonApiKeyCredentialTypeInfo);

                var body = message.GetBody(format);
                Assert.Equal(expectedString, body);
            }
コード例 #11
0
        private string GetBodyInternal(EmailFormat format)
        {
            var warningMessages = GetWarningMessages();

            var markdown = $@"The symbol package [{_symbolPackage.Id} {_symbolPackage.Version}]({_packageUrl}) was recently published on {_configuration.GalleryOwner.DisplayName} by {_symbolPackage.Package.User.Username}. If this was not intended, please [contact support]({_packageSupportUrl}).";

            if (!string.IsNullOrEmpty(warningMessages))
            {
                markdown += warningMessages;
            }

            string body;

            switch (format)
            {
            case EmailFormat.PlainText:
                body = ToPlainText(markdown);
                break;

            case EmailFormat.Markdown:
                body = markdown;
                break;

            case EmailFormat.Html:
                body = Markdown.ToHtml(markdown);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(format));
            }

            return(body + EmailMessageFooter.ForPackageOwnerNotifications(format, _configuration.GalleryOwner.DisplayName, _emailSettingsUrl));
        }
 public void OutputEmailFormat(EmailFormat valueSet)
 {
     OutputStatusMessage(string.Format("Values in {0}", valueSet.GetType()));
     foreach (var value in Enum.GetValues(typeof(EmailFormat)))
     {
         OutputStatusMessage(value.ToString());
     }
 }
コード例 #13
0
            public void ReturnsExpectedBodyForNonAdmin(EmailFormat format, string expectedString)
            {
                var message = CreateMessage(newUserEmailAllowed: true);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #14
0
            public void ReturnsExpectedBodyForUser(EmailFormat format, string expectedString)
            {
                var message = CreateMessage(Fakes.UnconfirmedUser);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #15
0
            public void ReturnsExpectedBodyForOrganization(EmailFormat format, string expectedString)
            {
                var message = CreateMessage(isOrganization: true);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
            public void ReturnsExpectedBody(EmailFormat format, string expectedString, bool isNewOwnerOrganization)
            {
                var message = CreateMessage(isNewOwnerOrganization: isNewOwnerOrganization);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #17
0
 public static string ForContactOwnerNotifications(EmailFormat format, string galleryOwnerDisplayName, string emailSettingsUrl)
 {
     return(ForReason(
                format,
                galleryOwnerDisplayName,
                emailSettingsUrl,
                "To stop receiving contact emails as an owner of this package"));
 }
コード例 #18
0
            public void ReturnsExpectedBodyForAdmin(EmailFormat format, string expectedString)
            {
                var message = CreateMessage(organizationEmailAllowed: true, isAdmin: true);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #19
0
            public void ReturnsExpectedBody(EmailFormat format, string expectedString)
            {
                var message = CreateMessage();

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #20
0
ファイル: OutlookEmailExporter.cs プロジェクト: zhk/greenshot
        /// <summary>
        /// Helper method to get the Outlook signature
        /// </summary>
        /// <returns></returns>
        private static string GetOutlookSignature(EmailFormat format)
        {
            using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(ProfilesKey, false)) {
                if (profilesKey == null)
                {
                    return(null);
                }
                string defaultProfile = (string)profilesKey.GetValue(DefaultProfileValue);
                Log.DebugFormat("defaultProfile={0}", defaultProfile);
                using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + AccountKey, false)) {
                    if (profileKey != null)
                    {
                        string[] numbers = profileKey.GetSubKeyNames();
                        foreach (string number in numbers)
                        {
                            Log.DebugFormat("Found subkey {0}", number);
                            using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) {
                                if (numberKey != null)
                                {
                                    byte[] val = (byte[])numberKey.GetValue(NewSignatureValue);
                                    if (val == null)
                                    {
                                        continue;
                                    }
                                    string signatureName = "";
                                    foreach (byte b in val)
                                    {
                                        if (b != 0)
                                        {
                                            signatureName += (char)b;
                                        }
                                    }
                                    Log.DebugFormat("Found email signature: {0}", signatureName);
                                    string extension;
                                    switch (format)
                                    {
                                    case EmailFormat.Text:
                                        extension = ".txt";
                                        break;

                                    default:
                                        extension = ".htm";
                                        break;
                                    }
                                    string signatureFile = Path.Combine(SignaturePath, signatureName + extension);
                                    if (File.Exists(signatureFile))
                                    {
                                        Log.DebugFormat("Found email signature file: {0}", signatureFile);
                                        return(File.ReadAllText(signatureFile, Encoding.Default));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
コード例 #21
0
ファイル: Email.cs プロジェクト: radtek/genebank-gg_server
 /// <summary>
 ///
 /// </summary>
 /// <param name="to"></param>
 /// <param name="from"></param>
 /// <param name="cc"></param>
 /// <param name="bcc"></param>
 /// <param name="subject"></param>
 /// <param name="body"></param>
 /// <param name="format"></param>
 /// <param name="priority"></param>
 public Email(string to, string from, string cc, string bcc, string subject, string body, EmailFormat format, EmailPriority priority) : this()
 {
     _to       = to;
     _from     = from;
     _cc       = cc;
     _bcc      = bcc;
     _subject  = subject;
     _body     = body;
     _format   = format;
     _priority = priority;
 }
コード例 #22
0
            public void ReturnsExpectedBodyForCredentialWithNullDescription(EmailFormat format, string expectedString)
            {
                var credential = new Credential();

                credential.User = Fakes.RequestingUser;

                var message = CreateMessage(credential);

                var body = message.GetBody(format);

                Assert.Equal(expectedString, body);
            }
コード例 #23
0
 public FacadeEmail()
 {
     _email       = new Email(_conf);
     _emailFormat = new EmailFormatTxt();
     _msg         = new EmailMessage("", _emailFormat);
     _conf        = new SmtpSettings()
     {
         ServerName = "smt.gmail.com",
         Password   = "******",
         UserName   = "******"
     };
 }
コード例 #24
0
        public string GetBody(EmailFormat format)
        {
            switch (format)
            {
            case EmailFormat.PlainText:
                return(GetPlainTextBody());

            case EmailFormat.Markdown:
                return(GetMarkdownBody());

            default:
                throw new ArgumentOutOfRangeException(nameof(format));
            }
        }
コード例 #25
0
        /// <summary>
        /// Helper method to create an outlook mail item with attachment
        /// </summary>
        /// <param name="tmpfile">The file to send, do not delete the file right away!</param>
        /// <returns>true if it worked, false if not</returns>
        public static bool ExportToOutlook(EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url)
        {
            bool exported = false;

            try {
                using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
                    if (outlookApplication != null)
                    {
                        ExportToNewEmail(outlookApplication, format, tmpFile, subject, attachmentName, to, CC, BCC, url);
                        exported = true;
                    }
                }
                return(exported);
            } catch (Exception e) {
                LOG.Error("Error while creating an outlook mail item: ", e);
            }
            return(exported);
        }
コード例 #26
0
        void Combobox_languageSelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the combobox values BEFORE changing the language
            EmailFormat       selectedEmailFormat       = GetSelected <EmailFormat>(combobox_emailformat);
            WindowCaptureMode selectedWindowCaptureMode = GetSelected <WindowCaptureMode>(combobox_window_capture_mode);

            if (combobox_language.SelectedItem != null)
            {
                LOG.Debug("Setting language to: " + (string)combobox_language.SelectedValue);
                lang.SetLanguage((string)combobox_language.SelectedValue);
            }
            // Reflect language changes to the settings form
            UpdateUI();

            // Update the email & windows capture mode
            SetEmailFormat(selectedEmailFormat);
            SetWindowCaptureMode(selectedWindowCaptureMode);
        }
コード例 #27
0
        /// <summary>
        /// Convert mail message to target format
        /// </summary>
        /// <param name="name">File name. e.g. myEmail.msg</param>
        /// <param name="format">Email format. e.g Eml, Msg, Mht</param>
        /// <param name="folder">Folder path.</param>
        /// <param name="outPath">Path to save result. It can be a local path e.g c:\file.eml or cloud storage path e.g. MyFolder/file.eml</param>
        /// <param name="storage">The document storage.</param>
        public void ConvertMailMessageToTargetFormat(string name, EmailFormat format, string folder, string outPath, string storage = "")
        {
            // GET  email/{name}?appSid={appSid}&format={format}&storage={storage}&folder={folder}&outPath={outPath}

            string apiUrl = string.Format(@"email/{0}?format={1}&storage={2}&folder={3}&outPath={4}",
                                          name, format, storage, folder, (outPath.Contains(@":\") ? string.Empty : outPath));

            if (!string.IsNullOrEmpty(outPath) && Directory.Exists(Path.GetDirectoryName(outPath)))
            {
                using (Stream responseStream = ServiceController.GetStream(apiUrl, AppSid, AppKey))
                    using (Stream file = File.OpenWrite(outPath))
                    {
                        ServiceController.CopyStream(responseStream, file);
                    }
            }
            else
            {
                ServiceController.Get(apiUrl, AppSid, AppKey);
            }
        }
コード例 #28
0
        public EmailFormat SplitMsgText(string msgText)
        {
            EmailFormat emailformat = new EmailFormat();

            #region --get email detail(split)

            string[] MailDetails = msgText.Split(new string[] { "akjshdyt45lkh" }, StringSplitOptions.None);

            emailformat.EmailDetailsId   = Convert.ToInt64(MailDetails[0].ToString());
            emailformat.EmailTempletId   = Convert.ToInt64(MailDetails[1].ToString());
            emailformat.UserMembershipId = Convert.ToInt64(MailDetails[2].ToString());
            emailformat.EmailFrom        = MailDetails[3].ToString();
            emailformat.EmailTo          = MailDetails[4].ToString();
            emailformat.EmailSubject     = MailDetails[5].ToString();
            emailformat.EmailBody        = MailDetails[6].ToString();
            emailformat.FirstName        = MailDetails[7].ToString();
            #endregion
            emailformat.InProcess = true;

            return(emailformat);
        }
コード例 #29
0
        /// <summary>
        /// Convert mail message to target format
        /// </summary>
        /// <param name="name">File name. e.g. myEmail.msg</param>
        /// <param name="format">Email format. e.g Eml, Msg, Mht</param>
        /// <param name="folder">Folder path.</param>
        /// <param name="outPath">Path to save result. It can be a local path e.g c:\file.eml or cloud storage path e.g. MyFolder/file.eml</param>
        /// <param name="storage">The document storage.</param>
        public void ConvertMailMessageToTargetFormat(string name, EmailFormat format, string folder, string outPath, string storage = "")
        {
            // GET 	email/{name}?appSid={appSid}&format={format}&storage={storage}&folder={folder}&outPath={outPath}

            string apiUrl = string.Format(@"email/{0}?format={1}&storage={2}&folder={3}&outPath={4}",
                                            name, format, storage, folder, (outPath.Contains(@":\") ? string.Empty : outPath));

            if (!string.IsNullOrEmpty(outPath) && Directory.Exists(Path.GetDirectoryName(outPath)))
            {
                using (Stream responseStream = ServiceController.GetStream(apiUrl, AppSid, AppKey))
                using (Stream file = File.OpenWrite(outPath))
                {
                    ServiceController.CopyStream(responseStream, file);
                }
            }
            else
            {
                ServiceController.Get(apiUrl, AppSid, AppKey);
            }

        }
コード例 #30
0
ファイル: EmailHelper.cs プロジェクト: ParamaBiswas/Hnm
        public void SendMail(string obj_Pk, int moduleID, string userid)
        {
            EmailFormat objEmailFormat = new EmailFormat();

            objEmailFormat = GetEmailFormat(moduleID);
            string      username   = GetUserId(userid);
            MailMessage mail       = new MailMessage();
            SmtpClient  SmtpServer = new SmtpClient("smtp-mail.outlook.com");

            mail.From = new MailAddress("*****@*****.**", "Center Point");
            mail.To.Add(username);
            mail.Subject = objEmailFormat.EmailSubject;
            var replacement = objEmailFormat.EmailBody.Replace("@PARAMETER@", obj_Pk);

            mail.Body                        = replacement;
            mail.IsBodyHtml                  = true;
            SmtpServer.Port                  = 587;
            SmtpServer.DeliveryMethod        = SmtpDeliveryMethod.Network;
            SmtpServer.UseDefaultCredentials = false;
            SmtpServer.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "Dhaka@2013");
            SmtpServer.EnableSsl             = true;

            SmtpServer.Send(mail);
        }
コード例 #31
0
        public static void SendWithFile(string fromAddress, string toAddress, string subject, string body, EmailFormat format, List<ImagesResourceEmail> resourceList, List<FileReport> files)
        {
            SmtpClient smtp = GetSmtpClient();
            MailMessage message = new MailMessage();

            // Send the email
            try
            {
                // Set the from address
                if (fromAddress.IndexOf(',') >= 0)
                    fromAddress = fromAddress.Substring(0, fromAddress.IndexOf(','));

                message.Priority = MailPriority.High;

                message.From = new MailAddress(fromAddress);




                if (resourceList != null && resourceList.Count() > 0)
                {
                    AlternateView av1 = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

                    foreach (ImagesResourceEmail item in resourceList)
                    {
                        LinkedResource img = new LinkedResource(item.Url);
                        img.ContentId = item.Id;

                        av1.LinkedResources.Add(img);
                    }

                    message.AlternateViews.Add(av1);
                }
                else
                {
                    message.Body = body;
                }



                // Set the to address
                if (!string.IsNullOrEmpty(toAddress))
                {
                    AddToAddress(toAddress, message);
                }



                // Set the email subject and body
                message.Subject = subject;

                message.IsBodyHtml = format == EmailFormat.HTML;
                if (files != null)
                {
                    foreach (FileReport file in files)
                    {

                        System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(file.ContentType);
                        System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(file.MemoryStream, ct);
                        attach.ContentDisposition.FileName = file.FileName;
                        message.Attachments.Add(attach);
                    }
                }

                smtp.Send(message);
            }
            catch (SmtpException smtpEx)
            {
                throw smtpEx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #32
0
		/// <summary>
		/// Helper method to get the Outlook signature
		/// </summary>
		/// <returns></returns>
		private static string GetOutlookSignature(EmailFormat format) {
			using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(PROFILES_KEY, false)) {
				if (profilesKey == null) {
					return null;
				}
				string defaultProfile = (string)profilesKey.GetValue(DEFAULT_PROFILE_VALUE);
				LOG.DebugFormat("defaultProfile={0}", defaultProfile);
				using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + ACCOUNT_KEY, false)) {
					if (profilesKey == null) {
						return null;
					}
					string[] numbers = profileKey.GetSubKeyNames();
					foreach (string number in numbers) {
						LOG.DebugFormat("Found subkey {0}", number);
						using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) {
							byte[] val = (byte[])numberKey.GetValue(NEW_SIGNATURE_VALUE);
							if (val == null) {
								continue;
							}
							string signatureName = "";
							foreach (byte b in val) {
								if (b != 0) {
									signatureName += (char)b;
								}
							}
							LOG.DebugFormat("Found email signature: {0}", signatureName);
							string extension;
							switch (format) {
								case EmailFormat.Text:
									extension = ".txt";
									break;
								case EmailFormat.HTML:
								default:
									extension = ".htm";
									break;
							}
							string signatureFile = Path.Combine(SIGNATURE_PATH, signatureName + extension);
							if (File.Exists(signatureFile)) {
								LOG.DebugFormat("Found email signature file: {0}", signatureFile);
								return File.ReadAllText(signatureFile, Encoding.Default);
							}
						}
					}
				}
			}
			return null;
		}
コード例 #33
0
		/// <summary>
		/// Helper method to create an outlook mail item with attachment
		/// </summary>
		/// <param name="tmpfile">The file to send, do not delete the file right away!</param>
		/// <returns>true if it worked, false if not</returns>
		public static bool ExportToOutlook(EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url) {
			bool exported = false;
			try {
				using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
					if (outlookApplication != null) {
						ExportToNewEmail(outlookApplication, format, tmpFile, subject, attachmentName, to, CC, BCC, url);
						exported = true;
					}
				}
				return exported;
			} catch (Exception e) {
				LOG.Error("Error while creating an outlook mail item: ", e);
			}
			return exported;
		}
コード例 #34
0
		/// <summary>
		/// Export image to a new email
		/// </summary>
		/// <param name="outlookApplication"></param>
		/// <param name="tmpFile"></param>
		/// <param name="captureDetails"></param>
		private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url) {
			using (IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem)) {
				if (newItem == null) {
					return;
				}
				//MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
				MailItem newMail = (MailItem)newItem;
				newMail.Subject = subject;
				if (!string.IsNullOrEmpty(to)) {
					newMail.To = to;
				}
				if (!string.IsNullOrEmpty(CC)) {
					newMail.CC = CC;
				}
				if (!string.IsNullOrEmpty(BCC)) {
					newMail.BCC = BCC;
				}
				newMail.BodyFormat = OlBodyFormat.olFormatHTML;
				string bodyString = null;
				// Read the default signature, if nothing found use empty email
				try {
					bodyString = GetOutlookSignature(format);
				} catch (Exception e) {
					LOG.Error("Problem reading signature!", e);
				}
				switch (format) {
					case EmailFormat.Text:
						// Create the attachment (and dispose the COM object after using)
						using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName)) {
							newMail.BodyFormat = OlBodyFormat.olFormatPlain;
							if (bodyString == null) {
								bodyString = "";
							}
							newMail.Body = bodyString;
						}
						break;
					case EmailFormat.HTML:
					default:
						string contentID = Path.GetFileName(tmpFile);
						// Create the attachment (and dispose the COM object after using)
						using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
							// add content ID to the attachment
							if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) {
								try {
									contentID = Guid.NewGuid().ToString();
									IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
									propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
								} catch {
									LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
									contentID = Path.GetFileName(tmpFile);
								}
							}
						}

						newMail.BodyFormat = OlBodyFormat.olFormatHTML;
						string href = "";
						string hrefEnd = "";
						if (!string.IsNullOrEmpty(url)) {
							href = string.Format("<A HREF=\"{0}\">", url);
							hrefEnd = "</A>";
						}
						string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd);
						string fallbackBody = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded);
						if (bodyString == null) {
							bodyString = fallbackBody;
						} else {
							int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
							if (bodyIndex >= 0) {
								bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
								if (bodyIndex >= 0) {
									bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
								} else {
									bodyString = fallbackBody;
								}
							} else {
								bodyString = fallbackBody;
							}
						}
						newMail.HTMLBody = bodyString;
						break;
				}
				// So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
				newMail.Display(false);

				using (IInspector inspector = newMail.GetInspector()) {
					if (inspector != null) {
						try {
							inspector.Activate();
						} catch {
							// Ignore
						}
					}
				}
			}
		}
コード例 #35
0
        public virtual void SendEmail(EmailFormat format, string messageTypeID, string messageTypeCategory, string recipientEmail, Dictionary <string, string> tokenValues, string[] ccRecipients = null)
        {
            base.ExecuteMethod("PrepareAndSend", delegate()
            {
                IEmailTransport transport = this.IFoundation.SafeResolve <IEmailTransport>();
                if (transport != null)
                {
                    string templateKey = "EmailTemplate_" + format.ToString();
                    string subjectKey  = "EmailTemplate_" + format.ToString() + "_Subject";

                    string bodyTemplate = this.Cache.PerLifetime(templateKey, delegate()
                    {
                        return(this.API.Direct.GlobalSettings.GetValueOrDefault(templateKey, ""));
                    });
                    string subjectTemplate = this.Cache.PerLifetime(subjectKey, delegate()
                    {
                        return(this.API.Direct.GlobalSettings.GetValueOrDefault(subjectKey, ""));
                    });

                    if (string.IsNullOrEmpty(bodyTemplate) || string.IsNullOrEmpty(subjectTemplate))
                    {
                        this.SendAdminEmail("Flawed Configuration", "No Email Subject, Body Template found for: " + format.ToString());
                        return;
                    }

                    EmailRecipient recipient = new EmailRecipient(recipientEmail);
                    IEmail email             = transport.CreateEmail();
                    email.FromEmail          = this.Cache.PerLifetime("Email_FromEmail", delegate()
                    {
                        return(this.API.Direct.GlobalSettings.GetValueOrDefault("EmailFromEmail_Standard", "*****@*****.**"));
                    });
                    email.FromName = this.Cache.PerLifetime("Email_FromName", delegate()
                    {
                        return(this.API.Direct.GlobalSettings.GetValueOrDefault("EmailFromName_Standard", "Stencil"));
                    });
                    email.InternalMessageType = messageTypeCategory;
                    email.InternalTypeID      = messageTypeID;
                    email.HTMLBody            = this.ProcessTemplate(bodyTemplate, recipientEmail, tokenValues);
                    email.Subject             = this.ProcessTemplate(subjectTemplate, recipientEmail, tokenValues);
                    if (ccRecipients != null && ccRecipients.Length > 0)
                    {
                        if (email.ExtraData == null)
                        {
                            email.ExtraData = new Dictionary <string, string>();
                        }
                        email.ExtraData["cc"] = string.Join(";", ccRecipients);
                    }

                    if (string.IsNullOrEmpty(email.Subject))
                    {
                        email.Subject = "Information";
                    }
                    if (tokenValues.ContainsKey("FromName"))
                    {
                        email.FromName = tokenValues["FromName"];
                    }
                    if (tokenValues.ContainsKey("FromEmail"))
                    {
                        email.FromEmail = tokenValues["FromEmail"];
                    }

                    transport.SendEmail(email, recipient, false);
                }
            });
        }
コード例 #36
0
 /// <summary>
 /// This method will be called after reading the configuration, so eventually some corrections can be made
 /// </summary>
 public override void AfterLoad()
 {
     if (OutputDestinations == null)
      {
     OutputDestinations = new List<Destination>();
      }
      // Make sure there is an output!
      if (OutputDestinations.Count == 0)
      {
     OutputDestinations.Add(Destination.Editor);
      }
      // Check for Outlook, if it's not installed force email format to MAPI
      if (OutputEMailFormat != EmailFormat.MAPI && !EmailConfigHelper.HasOutlook())
      {
     OutputEMailFormat = EmailFormat.MAPI;
      }
      // Prevent both settings at once, bug #3435056
      if (OutputDestinations.Contains(Destination.Clipboard) && OutputFileCopyPathToClipboard)
      {
     OutputFileCopyPathToClipboard = false;
      }
      if (AutoCropDifference < 0)
      {
     AutoCropDifference = 0;
      }
      if (AutoCropDifference > 255)
      {
     AutoCropDifference = 255;
      }
 }
コード例 #37
0
 public static void Send(string fromAddress, string toAddress, string toBcc, string subject, string body, EmailFormat format)
 {
     Send(fromAddress, toAddress, toBcc, subject, body, format, null, null);
 }
コード例 #38
0
 public static void Send(string fromAddress, string toAddress, string subject, string body, EmailFormat format, List<ImagesResourceEmail> resourceList)
 {
     Send(fromAddress, toAddress, null, subject, body, format, resourceList, null);
 }
コード例 #39
0
        public static void Send(string fromAddress, string toAddress, string toBcc, string subject, string body, EmailFormat format, List<ImagesResourceEmail> resourceList, params string[] files)
        {
            SmtpClient smtp = GetSmtpClient();
            MailMessage message = new MailMessage();

            // Send the email
            try
            {
                // Set the from address
                if (fromAddress.IndexOf(',') >= 0)
                    fromAddress = fromAddress.Substring(0, fromAddress.IndexOf(','));

                message.Priority = MailPriority.High;

                message.From = new MailAddress(fromAddress);




                if (resourceList != null && resourceList.Count() > 0)
                {
                    AlternateView av1 = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

                    foreach (ImagesResourceEmail item in resourceList)
                    {
                        LinkedResource img = new LinkedResource(item.Url);
                        img.ContentId = item.Id;

                        av1.LinkedResources.Add(img);
                    }

                    message.AlternateViews.Add(av1);
                }
                else
                {
                    message.Body = body;
                }



                // Set the to address
                if (!string.IsNullOrEmpty(toAddress))
                    AddToAddress(toAddress, message);

                if (!string.IsNullOrEmpty(toBcc))
                {
                    // Set the toBcc address
                    AddToBccAddress(toBcc, message);
                }

                // Set the email subject and body
                message.Subject = subject;

                message.IsBodyHtml = format == EmailFormat.HTML;
                if (files != null)
                    foreach (string file in files)
                        message.Attachments.Add(new Attachment(file));

                smtp.Send(message);
            }
            catch (SmtpException smtpEx)
            {
                throw smtpEx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #40
0
        /// <summary>
        /// Export image to a new email
        /// </summary>
        /// <param name="outlookApplication"></param>
        /// <param name="tmpFile"></param>
        /// <param name="captureDetails"></param>
        private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName)
        {
            Item newItem = outlookApplication.CreateItem(OlItemType.olMailItem);
            if (newItem == null) {
                return;
            }
            //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
            MailItem newMail = (MailItem)newItem;
            newMail.Subject = subject;
            newMail.BodyFormat = OlBodyFormat.olFormatHTML;
            string bodyString = null;
            // Read the default signature, if nothing found use empty email
            try {
                bodyString = GetOutlookSignature(format);
            } catch (Exception e) {
                LOG.Error("Problem reading signature!", e);
            }
            switch (format) {
                case EmailFormat.Text:
                    newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName);
                    newMail.BodyFormat = OlBodyFormat.olFormatPlain;
                    if (bodyString == null) {
                        bodyString = "";
                    }
                    newMail.Body = bodyString;
                    break;
                case EmailFormat.HTML:
                default:
                    // Create the attachment
                    Attachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName);
                    // add content ID to the attachment
                    string contentID = Path.GetFileName(tmpFile);
                    if (outlookVersion.Major >= 12) {
                        // Add the content id to the attachment
                        try {
                            contentID = Guid.NewGuid().ToString();
                            PropertyAccessor propertyAccessor = attachment.PropertyAccessor;
                            propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
                        } catch {
                            LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
                            contentID = Path.GetFileName(tmpFile);
                        }
                    }

                    newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                    string htmlImgEmbedded = "<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>";
                    string fallbackBody = "<HTML><BODY>" + htmlImgEmbedded + "</BODY></HTML>";
                    if (bodyString == null) {
                        bodyString = fallbackBody;
                    } else {
                        int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
                        if (bodyIndex >= 0) {
                            bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
                            if (bodyIndex >= 0) {
                                bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
                            } else {
                                bodyString = fallbackBody;
                            }
                        } else {
                            bodyString = fallbackBody;
                        }
                    }
                    newMail.HTMLBody = bodyString;
                    break;
            }
            // So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
            try {
                newMail.Display(false);
                newMail.GetInspector().Activate();
            } catch (Exception ex) {
                LOG.WarnFormat("Problem displaying the new email, retrying to display it. Problem: {0}", ex.Message);
                Thread retryDisplayEmail = new Thread(delegate() {
                    int retries = 60;
                    int retryInXSeconds = 5;
                    while (retries-- > 0) {
                        Thread.Sleep(retryInXSeconds * 1000);
                        try {
                            newMail.Display(false);
                            newMail.GetInspector().Activate();
                            LOG.InfoFormat("Managed to display the message.");
                            return;
                        } catch (Exception) {
                            LOG.WarnFormat("Retrying to show email in {0} seconds... Retries left: {1}", retryInXSeconds, retries);
                        }
                    }
                    LOG.WarnFormat("Retry failed, saving message to draft.");
                    newMail.Save();
                });
                retryDisplayEmail.Name = "Retry to display email";
                retryDisplayEmail.IsBackground = true;
                retryDisplayEmail.Start();
            }
        }