mirror of
https://github.com/Muskingum-County-Library-System/Send2Email.git
synced 2025-04-19 11:59:49 -04:00
Updated to use Encryption for smtp_password, and added some QOL features
This commit is contained in:
parent
ba537545e2
commit
3ec05584ad
BIN
.vs/ProjectEvaluation/scan2email.metadata.v7.bin
Normal file
BIN
.vs/ProjectEvaluation/scan2email.metadata.v7.bin
Normal file
Binary file not shown.
BIN
.vs/ProjectEvaluation/scan2email.projects.v7.bin
Normal file
BIN
.vs/ProjectEvaluation/scan2email.projects.v7.bin
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
.vs/Scan2Email/v17/.futdcache.v2
Normal file
BIN
.vs/Scan2Email/v17/.futdcache.v2
Normal file
Binary file not shown.
BIN
.vs/Scan2Email/v17/.suo
Normal file
BIN
.vs/Scan2Email/v17/.suo
Normal file
Binary file not shown.
@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Windows.Forms;
|
||||
|
||||
|
||||
namespace SendEmail
|
||||
{
|
||||
public partial class Form1 : Form
|
||||
@ -10,47 +9,45 @@ namespace SendEmail
|
||||
* Form1 is the main window for Send2Email
|
||||
*/
|
||||
#region UI
|
||||
public Form1() //Autogenerated Code Block
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void ExitClick(object sender, EventArgs e)
|
||||
{
|
||||
//Exit the application
|
||||
// Exit the application
|
||||
Application.Exit();
|
||||
}
|
||||
|
||||
private void ConfigClick(object sender, EventArgs e)
|
||||
{
|
||||
this.Hide(); //Hide Form1
|
||||
var form2 = new Form2(); //Create Form 2
|
||||
form2.Closed += (s, args) => this.Show(); //Attach this.Show() to the Form2.Close() eventhandler, which will show Form1 when Form2 closes.
|
||||
form2.Show(); //Show Form2
|
||||
this.Hide(); // Hide Form1
|
||||
var form2 = new Form2(); // Create Form 2
|
||||
form2.Closed += (s, args) => this.Show(); // Attach this.Show() to the Form2.Close() eventhandler, which will show Form1 when Form2 closes.
|
||||
form2.Show(); // Show Form2
|
||||
}
|
||||
|
||||
private void SendClick(object sender, EventArgs e)
|
||||
{
|
||||
string email = EmailInput.Text; //Get Email from Text Input
|
||||
//Checks if email is valid, this does not check if the email address DOES exist, just if it CAN exist
|
||||
if (Program.IsValidEmail(email)) //If email is valid
|
||||
string email = EmailInput.Text; // Get Email from Text Input
|
||||
// Checks if email is valid, this does not check if the email address DOES exist, just if it CAN exist
|
||||
if (Program.IsValidEmail(email)) // If email is valid
|
||||
{
|
||||
Program.Send(email); //Sends valid email to Send() function from within Program.cs
|
||||
Program.Send(email); // Sends valid email to Send() function from within Program.cs
|
||||
}
|
||||
else //If the email is not valid
|
||||
else // If the email is not valid
|
||||
{
|
||||
//Error Message for invalid email
|
||||
// Error Message for invalid email
|
||||
MessageBox.Show(email + " is not a valid email address.\r\nPlease enter a valid email address.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
//Check if enter key is pressed in email address input
|
||||
// Check if enter key is pressed in email address input
|
||||
private void CheckEnter(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.Return) //If enter key pressed run the SendClick() function
|
||||
if (e.KeyCode == Keys.Return) // If enter key pressed run the SendClick() function
|
||||
{
|
||||
SendClick(sender, e);
|
||||
}
|
||||
|
@ -14,45 +14,46 @@ namespace SendEmail
|
||||
* Form2 is only the password prompt to enter the configuration menu
|
||||
*/
|
||||
|
||||
//Global Variables
|
||||
int wrongCount = 0; //Counts how many times the password is entered incorrectly
|
||||
const int LIMIT = 5; //The amount of times a password can be tried before exiting
|
||||
// Global Variables
|
||||
int wrongCount = 0; // Counts how many times the password is entered incorrectly
|
||||
const int LIMIT = 5; // The amount of times a password can be tried before exiting
|
||||
|
||||
public Form2() //Autogenerated Code Block
|
||||
public Form2()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
//Checks the password entered
|
||||
// Checks the password entered
|
||||
private void PassButtonClick(object sender, EventArgs e)
|
||||
{
|
||||
string input = textBox1.Text;
|
||||
if (input == Program.smtp_pass) //If password is correct
|
||||
string encryptedInput = Program.Encrypt(input); // Encrypt the user input
|
||||
if (encryptedInput == Program.smtp_pass) // If encrypted password is correct
|
||||
{
|
||||
this.Hide(); //Hide Form2
|
||||
var form3 = new Form3(); //Create Form3
|
||||
form3.Closed += (s, args) => this.Close(); //Attach this.Show() to the Form3.Close() eventhandler, which will show Form2 when Form3 closes.
|
||||
form3.Show(); //Show Form3
|
||||
this.Hide(); // Hide Form2
|
||||
var form3 = new Form3(); // Create Form3
|
||||
form3.Closed += (s, args) => this.Close(); // Attach this.Show() to the Form3.Close() eventhandler, which will show Form2 when Form3 closes.
|
||||
form3.Show(); // Show Form3
|
||||
}
|
||||
else
|
||||
{
|
||||
wrongCount++; //Each time this code is reached the wrong counter increases by 1
|
||||
if(wrongCount == LIMIT) //If we've reached the limit
|
||||
wrongCount++; // Each time this code is reached the wrong counter increases by 1
|
||||
if (wrongCount == LIMIT) // If we've reached the limit
|
||||
{
|
||||
Application.Exit(); //Exit the application
|
||||
Application.Exit(); // Exit the application
|
||||
}
|
||||
else //If we haven't reached the limit
|
||||
else // If we haven't reached the limit
|
||||
{
|
||||
//Inform user the number of password attempts remaining.
|
||||
// Inform user the number of password attempts remaining.
|
||||
MessageBox.Show("Incorrect password. " + (LIMIT - wrongCount).ToString() + " attempts remaining.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Check if enter key is pressed in the password text box
|
||||
// Check if enter key is pressed in the password text box
|
||||
private void CheckEnter(object sender, KeyEventArgs e)
|
||||
{
|
||||
if(e.KeyCode == Keys.Return)
|
||||
if (e.KeyCode == Keys.Return)
|
||||
{
|
||||
PassButtonClick(sender, e);
|
||||
}
|
||||
|
@ -21,29 +21,29 @@ namespace SendEmail
|
||||
|
||||
#region UI
|
||||
|
||||
//Default info in the info textbox
|
||||
// Default info in the info textbox
|
||||
string defaultInfo = "Helpful information about each section will display here when you hover over a textbox with your mouse.";
|
||||
|
||||
public Form3() //Automatically generated codeblock
|
||||
public Form3()
|
||||
{
|
||||
InitializeComponent();
|
||||
SetInfoBox(defaultInfo);
|
||||
FillData();
|
||||
}
|
||||
|
||||
//This will set the info textbox's contents when you hover over an input field
|
||||
// This will set the info textbox's contents when you hover over an input field
|
||||
private void SetInfoBox(string input)
|
||||
{
|
||||
infoBox.Text = input;
|
||||
}
|
||||
|
||||
//Fill the input fields with the data from the config file
|
||||
// Fill the input fields with the data from the config file
|
||||
public void FillData()
|
||||
{
|
||||
hostTB.Text = Program.smtp_host;
|
||||
portTB.Text = Program.smtp_port.ToString();
|
||||
emailTB.Text = Program.smtp_user;
|
||||
passwordTB.Text = Program.smtp_pass;
|
||||
passwordTB.Text = Program.Decrypt(Program.smtp_pass); // Decrypt password for display
|
||||
|
||||
fromTB.Text = Program.mail_from;
|
||||
subjectTB.Text = Program.mail_subject;
|
||||
@ -53,17 +53,17 @@ namespace SendEmail
|
||||
extensionsTB.Text = Program.file_extensions;
|
||||
}
|
||||
|
||||
//Detects when mouse hovers over an input field and calls SetInfoBox() with updated info text
|
||||
// Detects when mouse hovers over an input field and calls SetInfoBox() with updated info text
|
||||
private void HoverInfo(object sender, EventArgs e)
|
||||
{
|
||||
TextBox holder = (TextBox)sender; //Hold onto the sender event that triggered HoverInfo()
|
||||
string holdName = holder.Name; //Get the name of the sender that triggered HoverInfo()
|
||||
TextBox holder = (TextBox)sender; // Hold onto the sender event that triggered HoverInfo()
|
||||
string holdName = holder.Name; // Get the name of the sender that triggered HoverInfo()
|
||||
string output;
|
||||
|
||||
switch (holdName) //Switch through the possible input fields and sets the output to the correct values
|
||||
switch (holdName) // Switch through the possible input fields and sets the output to the correct values
|
||||
{
|
||||
case "hostTB":
|
||||
output = "SMTP Host: SMTP Host. At the time of creation, we utalize Google's SMTP server located at smtp.google.com";
|
||||
output = "SMTP Host: SMTP Host. At the time of creation, we utilize Google's SMTP server located at smtp.google.com";
|
||||
break;
|
||||
case "portTB":
|
||||
output = "SMTP Port: SMTP Port";
|
||||
@ -94,20 +94,21 @@ namespace SendEmail
|
||||
break;
|
||||
}
|
||||
|
||||
SetInfoBox(output); //Send the output text to the info textbox
|
||||
SetInfoBox(output); // Send the output text to the info textbox
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Save/Load Configuration
|
||||
|
||||
//Save the configuration data, will overwrite existing settings
|
||||
// Save the configuration data, will overwrite existing settings
|
||||
// Save the configuration data, will overwrite existing settings
|
||||
private void SaveConfig(object sender, EventArgs e)
|
||||
{
|
||||
string cfg_host = hostTB.Text;
|
||||
string string_cfg_port = portTB.Text;
|
||||
string cfg_user = emailTB.Text;
|
||||
string cfg_pass = passwordTB.Text;
|
||||
string cfg_pass = Program.Encrypt(passwordTB.Text); // Encrypt the password
|
||||
|
||||
string cfg_from = fromTB.Text;
|
||||
string cfg_subject = subjectTB.Text;
|
||||
@ -118,37 +119,60 @@ namespace SendEmail
|
||||
|
||||
int cfg_port = Int32.Parse(string_cfg_port);
|
||||
|
||||
//Create a JSON object with the configuration data
|
||||
// Create a JSON object with the configuration data
|
||||
Config cfg = new Config(cfg_host, cfg_port, cfg_user, cfg_pass, cfg_from, cfg_subject, cfg_body, cfg_delivery, cfg_extensions);
|
||||
|
||||
//Serialize the JSON data so it can be written to a text file
|
||||
// Serialize the JSON data so it can be written to a text file
|
||||
string[] json = { JsonConvert.SerializeObject(cfg, Formatting.Indented) };
|
||||
|
||||
//Write Config file to Program.appPath (default is Appdata/Local/Send2Email)
|
||||
// Write Config file to Program.appPath (default is Appdata/Local/Send2Email)
|
||||
WriteFile(json, Program.configName, Program.configFileExt);
|
||||
|
||||
// Close Form3 and open Form1
|
||||
this.Hide();
|
||||
var form1 = new Form1();
|
||||
form1.Closed += (s, args) => this.Close();
|
||||
form1.Show();
|
||||
}
|
||||
|
||||
|
||||
public static bool LoadConfig() //Boolean method, returns true or false to whatever called LoadConfig
|
||||
public static bool LoadConfig() // Boolean method, returns true or false to whatever called LoadConfig
|
||||
{
|
||||
//Config filepath
|
||||
string cfg = Program.appPath + "/" + Program.configFileName;
|
||||
// Config filepath in AppData
|
||||
string cfgFilePath = Path.Combine(Program.appPath, Program.configFileName);
|
||||
// Example config filepath in the bin directory of the project
|
||||
string exampleCfgFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "example.cfg.json");
|
||||
|
||||
//Check if config file exists
|
||||
bool cExist = File.Exists(cfg);
|
||||
// Check if config file exists in AppData
|
||||
bool cExist = File.Exists(cfgFilePath);
|
||||
|
||||
if (!cExist) //If a config doesn't exist
|
||||
if (!cExist) // If a config doesn't exist
|
||||
{
|
||||
return false; //Return false for LoadConfig boolean
|
||||
// Check if example config exists in the bin directory of the project
|
||||
if (File.Exists(exampleCfgFilePath))
|
||||
{
|
||||
// Ensure the directory exists
|
||||
if (!Directory.Exists(Program.appPath))
|
||||
{
|
||||
Directory.CreateDirectory(Program.appPath);
|
||||
}
|
||||
else //Config file does exist
|
||||
|
||||
// Copy the example config to the AppData config file path
|
||||
File.Copy(exampleCfgFilePath, cfgFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
//Create an array to store the configuration file line by line
|
||||
// Display an error message before closing the application
|
||||
MessageBox.Show("A critical error has occurred. Example configuration file is missing. Please contact IT to resolve this issue.");
|
||||
return false; // Return false for LoadConfig boolean
|
||||
}
|
||||
}
|
||||
|
||||
// Create an array to store the configuration file line by line
|
||||
string[] cfgFile = ReadFile("cfg", "json");
|
||||
string cfgData = ConvertStringArray(cfgFile);
|
||||
|
||||
//Get the first line of our configuration
|
||||
|
||||
// Get the first line of our configuration
|
||||
Config config = JsonConvert.DeserializeObject<Config>(cfgData);
|
||||
|
||||
Program.smtp_host = config.SMTP_Host;
|
||||
@ -165,7 +189,7 @@ namespace SendEmail
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
@ -174,7 +198,6 @@ namespace SendEmail
|
||||
// Create a string array with the lines of text
|
||||
public static void WriteFile(string[] data, string fileName, string fileExtension)
|
||||
{
|
||||
|
||||
string temp = "";
|
||||
string file = fileName + "." + fileExtension;
|
||||
|
||||
@ -189,7 +212,6 @@ namespace SendEmail
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static string[] ReadFile(string fileName, string fileExtension)
|
||||
{
|
||||
string temp = "";
|
||||
@ -210,11 +232,11 @@ namespace SendEmail
|
||||
/* Takes a multi-line file and turns it into a single-line string
|
||||
* This is really only here because the JSON files are pretty-printed
|
||||
* for human readability, but it's much easier to work with the JSON
|
||||
* data as a single string rather than an array of string data*/
|
||||
* data as a single string rather than an array of string data */
|
||||
public static string ConvertStringArray(string[] input)
|
||||
{
|
||||
string output = "";
|
||||
foreach (string line in input) //Loop through input and append it to the end of output
|
||||
foreach (string line in input) // Loop through input and append it to the end of output
|
||||
{
|
||||
output += line;
|
||||
}
|
||||
@ -223,10 +245,6 @@ namespace SendEmail
|
||||
}
|
||||
|
||||
#region JSON Config
|
||||
/* Sources
|
||||
* https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
|
||||
* https://www.newtonsoft.com/json/help/html/SerializeWithJsonSerializerToFile.htm
|
||||
*/
|
||||
public class Config
|
||||
{
|
||||
public string SMTP_Host { get; set; }
|
||||
@ -256,11 +274,8 @@ namespace SendEmail
|
||||
File_Extensions = file_extensions;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -5,21 +5,22 @@ using System.Windows.Forms;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace SendEmail
|
||||
{
|
||||
class Program
|
||||
{
|
||||
#region Global Variables
|
||||
//File Explorer Path
|
||||
//C:\Users\[USER]\AppData\Local\Send2Email
|
||||
// File Explorer Path
|
||||
// C:\Users\[USER]\AppData\Local\Send2Email
|
||||
public static string appPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Send2Email\\";
|
||||
|
||||
//My Pictures Path
|
||||
//C:\Users\[USER]\My Pictures
|
||||
// My Pictures Path
|
||||
// C:\Users\[USER]\My Pictures
|
||||
public static string picPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
|
||||
|
||||
//Variables to be loaded from config file
|
||||
// Variables to be loaded from config file
|
||||
public static string configName = "cfg";
|
||||
public static string configFileExt = "json";
|
||||
public static string configFileName = configName + "." + configFileExt;
|
||||
@ -33,28 +34,113 @@ namespace SendEmail
|
||||
public static string mail_body;
|
||||
public static string mail_delivery;
|
||||
public static string file_extensions;
|
||||
|
||||
// Encryption keys (8 bytes for DES)
|
||||
public static string key_secret = "8byteKey";
|
||||
public static string key_public = "byte8Key";
|
||||
#endregion
|
||||
|
||||
#region Main Method
|
||||
[STAThread]
|
||||
static void Main() //Main method, this runs as soon as the software is started
|
||||
static void Main()
|
||||
{
|
||||
//Set up the basic requirements for a WinForms application
|
||||
// Set up the basic requirements for a WinForms application
|
||||
Application.SetHighDpiMode(HighDpiMode.SystemAware);
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
|
||||
|
||||
bool cont = Form3.LoadConfig(); //Load Configuration method
|
||||
if (cont) //If Config exists
|
||||
bool cont = Form3.LoadConfig(); // Load Configuration method
|
||||
if (cont) // If Config exists
|
||||
{
|
||||
Application.Run(new Form1()); //Open Form1 (Main Window)
|
||||
if (string.IsNullOrEmpty(smtp_pass)) // Check if password is empty
|
||||
{
|
||||
// Run first time setup
|
||||
Application.Run(new Form3());
|
||||
}
|
||||
else //If Config Doesn't Exist
|
||||
else
|
||||
{
|
||||
//Display an error message before closing the application
|
||||
Application.Run(new Form1()); // Open Form1 (Main Window)
|
||||
}
|
||||
}
|
||||
else // If Config Doesn't Exist
|
||||
{
|
||||
// Display an error message before closing the application
|
||||
MessageBox.Show("A critical error has occurred. Configuration file is missing. Send2Email will not function without this configuration file. Please contact IT to resolve this issue.");
|
||||
Application.Exit(); //Exit the application
|
||||
Application.Exit(); // Exit the application
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Encryption Methods
|
||||
public static string Encrypt(string input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string textToEncrypt = input;
|
||||
string ToReturn = "";
|
||||
byte[] secretkeyByte = System.Text.Encoding.UTF8.GetBytes(key_secret);
|
||||
byte[] publickeybyte = System.Text.Encoding.UTF8.GetBytes(key_public);
|
||||
byte[] inputbyteArray = System.Text.Encoding.UTF8.GetBytes(textToEncrypt);
|
||||
|
||||
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||||
{
|
||||
des.Mode = CipherMode.CBC;
|
||||
des.Padding = PaddingMode.PKCS7;
|
||||
des.Key = publickeybyte;
|
||||
des.IV = secretkeyByte;
|
||||
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
|
||||
{
|
||||
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
ToReturn = Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ToReturn;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message, ex.InnerException);
|
||||
}
|
||||
}
|
||||
|
||||
public static string Decrypt(string input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string textToDecrypt = input;
|
||||
string ToReturn = "";
|
||||
byte[] privatekeyByte = System.Text.Encoding.UTF8.GetBytes(key_secret);
|
||||
byte[] publickeybyte = System.Text.Encoding.UTF8.GetBytes(key_public);
|
||||
byte[] inputbyteArray = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
|
||||
|
||||
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||||
{
|
||||
des.Mode = CipherMode.CBC;
|
||||
des.Padding = PaddingMode.PKCS7;
|
||||
des.Key = publickeybyte;
|
||||
des.IV = privatekeyByte;
|
||||
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
|
||||
{
|
||||
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
ToReturn = System.Text.Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ToReturn;
|
||||
}
|
||||
catch (Exception ae)
|
||||
{
|
||||
throw new Exception(ae.Message, ae.InnerException);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@ -62,18 +148,16 @@ namespace SendEmail
|
||||
#region Email Methods
|
||||
|
||||
#region IsValidEmail
|
||||
//Checks if the email address entered is valid.
|
||||
//Source https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
|
||||
public static bool IsValidEmail(string email) //Accepts an email string and returns true if email is valid
|
||||
// Checks if the email address entered is valid.
|
||||
public static bool IsValidEmail(string email)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email)) //Null strings aren't valid so return false
|
||||
if (string.IsNullOrWhiteSpace(email)) // Null strings aren't valid so return false
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
// Normalize the domain
|
||||
email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
|
||||
RegexOptions.None, TimeSpan.FromMilliseconds(200));
|
||||
email = Regex.Replace(email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
|
||||
|
||||
// Examines the domain part of the email and normalizes it.
|
||||
string DomainMapper(Match match)
|
||||
@ -98,9 +182,7 @@ namespace SendEmail
|
||||
|
||||
try
|
||||
{
|
||||
return Regex.IsMatch(email,
|
||||
@"^[^@\s]+@[^@\s]+\.[^@\s]+$",
|
||||
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
|
||||
return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
@ -110,20 +192,19 @@ namespace SendEmail
|
||||
#endregion
|
||||
|
||||
#region Attachments
|
||||
//Checks files in Windows Pictures folder
|
||||
//returns filepaths with matching extensions
|
||||
// Checks files in Windows Pictures folder
|
||||
// returns filepaths with matching extensions
|
||||
public static string[] Attachments()
|
||||
{
|
||||
|
||||
string[] extensions;
|
||||
List<string> output = new List<string>(); //Holds the output
|
||||
List<string> output = new List<string>(); // Holds the output
|
||||
|
||||
try
|
||||
{
|
||||
extensions = file_extensions.Split(",");
|
||||
for (int e = 0; e < extensions.Length; e++)
|
||||
{
|
||||
extensions[e] = extensions[e].Trim(' '); //Remove any whitespace
|
||||
extensions[e] = extensions[e].Trim(' '); // Remove any whitespace
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -133,195 +214,64 @@ namespace SendEmail
|
||||
extensions = fill;
|
||||
}
|
||||
|
||||
string[] files = Directory.GetFiles(picPath); //Get array of all files in Pictures folder
|
||||
string[] files = Directory.GetFiles(picPath); // Get array of all files in Pictures folder
|
||||
|
||||
for (int i = 0; i < files.Length; i++) //Loop through all files
|
||||
for (int i = 0; i < files.Length; i++) // Loop through all files
|
||||
{
|
||||
string file = files[i]; //current file
|
||||
for(int j = 0; j < extensions.Length; j++) //Loop through all extensions for each file
|
||||
string file = files[i]; // current file
|
||||
for (int j = 0; j < extensions.Length; j++) // Loop through all extensions for each file
|
||||
{
|
||||
string footer = file.Substring(file.Length - extensions[j].Length);
|
||||
//If the file ends with an extension from our extensions array
|
||||
// If the file ends with an extension from our extensions array
|
||||
if (footer.ToString() == extensions[j].ToString())
|
||||
{
|
||||
output.Add(files[i]); //Add it to the output
|
||||
output.Add(files[i]); // Add it to the output
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output.ToArray(); // Return a list of all attachments
|
||||
}
|
||||
|
||||
return output.ToArray(); //Return a list of all attachments
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Send Email
|
||||
|
||||
public static void Send(string sendTo) //Send email function. This is where most of the work starts
|
||||
public static void Send(string sendTo)
|
||||
{
|
||||
string[] getAttachments = Attachments(); //Gets all valid attachment files in Pictures folder
|
||||
string[] getAttachments = Attachments(); // Gets all valid attachment files in Pictures folder
|
||||
|
||||
try
|
||||
{
|
||||
System.Net.Mail.Attachment attachment; //Create attachment variable
|
||||
MailMessage mail = new MailMessage(); //Create mail variable
|
||||
SmtpClient SmtpServer = new SmtpClient(smtp_host); //Create SmtpClient
|
||||
System.Net.Mail.Attachment attachment; // Create attachment variable
|
||||
MailMessage mail = new MailMessage(); // Create mail variable
|
||||
SmtpClient SmtpServer = new SmtpClient(smtp_host); // Create SmtpClient
|
||||
|
||||
//Load smtp/email settings from Configuration file
|
||||
// Load smtp/email settings from Configuration file
|
||||
SmtpServer.Port = smtp_port;
|
||||
mail.From = new MailAddress(mail_from);
|
||||
mail.Subject = mail_subject;
|
||||
mail.Body = mail_body;
|
||||
|
||||
mail.To.Add(sendTo.ToString()); //Get sendTo email from user input
|
||||
mail.To.Add(sendTo.ToString()); // Get sendTo email from user input
|
||||
|
||||
for(int i = 0; i < getAttachments.Length; i++) //Loop through each attachment
|
||||
for (int i = 0; i < getAttachments.Length; i++) // Loop through each attachment
|
||||
{
|
||||
attachment = new System.Net.Mail.Attachment(getAttachments[i]); //Set the attachment variable
|
||||
mail.Attachments.Add(attachment); //Attach the new attachment to the email
|
||||
attachment = new System.Net.Mail.Attachment(getAttachments[i]); // Set the attachment variable
|
||||
mail.Attachments.Add(attachment); // Attach the new attachment to the email
|
||||
}
|
||||
|
||||
SmtpServer.Credentials = new System.Net.NetworkCredential(smtp_user, smtp_pass); //Login to SMTP
|
||||
SmtpServer.EnableSsl = true; //Use SSL Encryption
|
||||
SmtpServer.Credentials = new System.Net.NetworkCredential(smtp_user, smtp_pass); // Login to SMTP
|
||||
SmtpServer.EnableSsl = true; // Use SSL Encryption
|
||||
|
||||
SmtpServer.Send(mail); //Send our mail variable
|
||||
MessageBox.Show(mail_delivery + sendTo); //Popup informs user where the email was sent
|
||||
SmtpServer.Send(mail); // Send our mail variable
|
||||
MessageBox.Show(mail_delivery + sendTo); // Popup informs user where the email was sent
|
||||
}
|
||||
catch (Exception ex) //If the Try fails the catch will output this error message.
|
||||
catch (Exception ex) // If the Try fails the catch will output this error message.
|
||||
{
|
||||
MessageBox.Show("A critical error has occured please contact IT \r\n" + ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region [ARCHIVE]
|
||||
/* This code is commented out, but it might be
|
||||
* useful if we ever need to work on the software
|
||||
* again in the future, so I've kept it archived. */
|
||||
|
||||
#region [ARCHIVE] Encryption, Decryption
|
||||
/*
|
||||
//Methods used to encrypt and decrypt a string
|
||||
//Source https://www.delftstack.com/howto/csharp/encrypt-and-decrypt-a-string-in-csharp/
|
||||
|
||||
public static string Encrypt(string input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string textToEncrypt = input;
|
||||
string ToReturn = "";
|
||||
byte[] secretkeyByte = { };
|
||||
secretkeyByte = System.Text.Encoding.UTF8.GetBytes(key_secret);
|
||||
byte[] publickeybyte = { };
|
||||
publickeybyte = System.Text.Encoding.UTF8.GetBytes(key_public);
|
||||
MemoryStream ms = null;
|
||||
CryptoStream cs = null;
|
||||
byte[] inputbyteArray = System.Text.Encoding.UTF8.GetBytes(textToEncrypt);
|
||||
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||||
{
|
||||
ms = new MemoryStream();
|
||||
cs = new CryptoStream(ms, des.CreateEncryptor(publickeybyte, secretkeyByte), CryptoStreamMode.Write);
|
||||
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
ToReturn = Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
return ToReturn;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message, ex.InnerException);
|
||||
}
|
||||
}
|
||||
|
||||
static string Decrypt(string input)
|
||||
{
|
||||
try
|
||||
{
|
||||
string textToDecrypt = input;
|
||||
string ToReturn = "";
|
||||
byte[] privatekeyByte = { };
|
||||
privatekeyByte = System.Text.Encoding.UTF8.GetBytes(key_secret);
|
||||
byte[] publickeybyte = { };
|
||||
publickeybyte = System.Text.Encoding.UTF8.GetBytes(key_public);
|
||||
MemoryStream ms = null;
|
||||
CryptoStream cs = null;
|
||||
byte[] inputbyteArray = new byte[textToDecrypt.Replace(" ", "+").Length];
|
||||
inputbyteArray = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
|
||||
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
|
||||
{
|
||||
ms = new MemoryStream();
|
||||
cs = new CryptoStream(ms, des.CreateDecryptor(publickeybyte, privatekeyByte), CryptoStreamMode.Write);
|
||||
cs.Write(inputbyteArray, 0, inputbyteArray.Length);
|
||||
cs.FlushFinalBlock();
|
||||
Encoding encoding = Encoding.UTF8;
|
||||
ToReturn = encoding.GetString(ms.ToArray());
|
||||
}
|
||||
return ToReturn;
|
||||
}
|
||||
catch (Exception ae)
|
||||
{
|
||||
throw new Exception(ae.Message, ae.InnerException);
|
||||
}
|
||||
}
|
||||
*/
|
||||
#endregion
|
||||
|
||||
#region [ARCHIVE] Encrypt/Decrypt Files
|
||||
/*
|
||||
public static void WriteEncryptedFile(string[] data, string fileName, string fileExtension)
|
||||
{
|
||||
|
||||
string temp = "";
|
||||
string file = fileName + "." + fileExtension;
|
||||
|
||||
// Write the string array to a new file named "WriteLines.txt".
|
||||
using (StreamWriter outputFile = new StreamWriter(Path.Combine(appPath, file)))
|
||||
{
|
||||
foreach (string line in data)
|
||||
{
|
||||
temp = Encrypt(line);
|
||||
}
|
||||
outputFile.WriteLine(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public static string[] ReadEncryptedFile(string fileName, string fileExtension)
|
||||
{
|
||||
string temp = "";
|
||||
string file = fileName + "." + fileExtension;
|
||||
|
||||
string[] lines = System.IO.File.ReadAllLines(Path.Combine(appPath, file));
|
||||
string[] output = new string[lines.Length];
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
temp = Decrypt(lines[i]);
|
||||
output[i] = temp;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
*/
|
||||
#endregion
|
||||
|
||||
#region [ARCHIVE] Keygen
|
||||
/*
|
||||
//Used origonally do generate public and secret keys
|
||||
public static string GenerateKey(int length)
|
||||
{
|
||||
//Random
|
||||
Random rand = new Random();
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
return new string(Enumerable.Repeat(chars, length).Select(s => s[rand.Next(s.Length)]).ToArray());
|
||||
}
|
||||
*/
|
||||
#endregion
|
||||
|
||||
#endregion
|
@ -2,7 +2,7 @@
|
||||
"SMTP_Host": "smtp.gmail.com",
|
||||
"SMTP_Port": 587,
|
||||
"SMTP_User": "email@company.com",
|
||||
"SMTP_Pass": "smtp_password",
|
||||
"SMTP_Pass": "",
|
||||
"Mail_From": "email@company.com",
|
||||
"Mail_Subject": "Mail Subject Text",
|
||||
"Mail_Body": "Mail Body Text",
|
||||
|
Loading…
x
Reference in New Issue
Block a user