Improve code style of Send-MailMessage cmdlet (#7723)

This commit is contained in:
ThreeFive-O
2018-09-08 23:19:48 +05:00
committed by Ilya
parent c7ed7129b2
commit dfe415e4ef
@@ -2,11 +2,11 @@
// Licensed under the MIT License.
using System;
using System.Text;
using System.Globalization;
using System.Net.Mail;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Net.Mail;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
@@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Commands
#region Command Line Parameters
/// <summary>
/// Specifies the files names to be attached to the email.
/// Gets or sets the files names to be attached to the email.
/// If the filename specified can not be found, then the relevant error
/// message should be thrown.
/// </summary>
@@ -28,65 +28,33 @@ namespace Microsoft.PowerShell.Commands
[ValidateNotNullOrEmpty]
[Alias("PsPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Attachments
{
get { return _attachments; }
set
{
_attachments = value;
}
}
private String[] _attachments;
public string[] Attachments { get; set; }
/// <summary>
/// Specifies the address collection that contains the
/// Gets or sets the address collection that contains the
/// blind carbon copy (BCC) recipients for the e-mail message.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Bcc
{
get { return _bcc; }
set
{
_bcc = value;
}
}
private String[] _bcc;
public string[] Bcc { get; set; }
/// <summary>
/// Specifies the body (content) of the message.
/// Gets or sets the body (content) of the message.
/// </summary>
[Parameter(Position = 2, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public String Body
{
get { return _body; }
set
{
_body = value;
}
}
private String _body;
public string Body { get; set; }
/// <summary>
/// Specifies a value indicating whether the mail message body is in Html.
/// Gets or sets the value indicating whether the mail message body is in Html.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("BAH")]
public SwitchParameter BodyAsHtml
{
get { return _bodyashtml; }
set
{
_bodyashtml = value;
}
}
private SwitchParameter _bodyashtml;
public SwitchParameter BodyAsHtml { get; set; }
/// <summary>
/// Specifies the encoding used for the content of the body and also the subject.
/// Gets or sets the encoding used for the content of the body and also the subject.
/// This is set to ASCII to ensure there are no problems with any email server.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
@@ -103,173 +71,96 @@ namespace Microsoft.PowerShell.Commands
EncodingConversion.Utf8NoBom,
EncodingConversion.Utf32
)]
[ArgumentToEncodingTransformationAttribute()]
[ArgumentToEncodingTransformationAttribute]
public Encoding Encoding { get; set; } = Encoding.ASCII;
/// <summary>
/// Specifies the address collection that contains the
/// Gets or sets the address collection that contains the
/// carbon copy (CC) recipients for the e-mail message.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cc")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Cc
{
get { return _cc; }
set
{
_cc = value;
}
}
private String[] _cc;
public string[] Cc { get; set; }
/// <summary>
/// Specifies the delivery notifications options for the e-mail message. The various
/// Gets or sets the delivery notifications options for the e-mail message. The various
/// options available for this parameter are None, OnSuccess, OnFailure, Delay and Never.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("DNO")]
[ValidateNotNullOrEmpty]
public DeliveryNotificationOptions DeliveryNotificationOption
{
get { return _deliverynotification; }
set
{
_deliverynotification = value;
}
}
private DeliveryNotificationOptions _deliverynotification;
public DeliveryNotificationOptions DeliveryNotificationOption { get; set; }
/// <summary>
/// Specifies the from address for this e-mail message. The default value for
/// Gets or sets the from address for this e-mail message. The default value for
/// this parameter is the email address of the currently logged on user.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public String From
{
get { return _from; }
set
{
_from = value;
}
}
private String _from;
public string From { get; set; }
/// <summary>
/// Specifies the name of the Host used to send the email. This host name will be assigned
/// Gets or sets the name of the Host used to send the email. This host name will be assigned
/// to the Powershell variable PSEmailServer, if this host can not reached an appropriate error.
/// message will be displayed.
/// </summary>
[Parameter(Position = 3, ValueFromPipelineByPropertyName = true)]
[Alias("ComputerName")]
[ValidateNotNullOrEmpty]
public String SmtpServer
{
get { return _smtpserver; }
set
{
_smtpserver = value;
}
}
private String _smtpserver;
public string SmtpServer { get; set; }
/// <summary>
/// Specifies the priority of the email message. The valid values for this are Normal, High and Low.
/// Gets or sets the priority of the email message. The valid values for this are Normal, High and Low.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public MailPriority Priority
{
get { return _priority; }
set
{
_priority = value;
}
}
private MailPriority _priority;
public MailPriority Priority { get; set; }
/// <summary>
/// Specifies the subject of the email message.
/// Gets or sets the subject of the email message.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)]
[Alias("sub")]
[ValidateNotNullOrEmpty]
public String Subject
{
get { return _subject; }
set
{
_subject = value;
}
}
private String _subject;
public string Subject { get; set; }
/// <summary>
/// Specifies the To address for this e-mail message.
/// Gets or sets the To address for this e-mail message.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] To
{
get { return _to; }
set
{
_to = value;
}
}
private String[] _to;
public string[] To { get; set; }
/// <summary>
/// Specifies the credential for this e-mail message.
/// Gets or sets the credential for this e-mail message.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[Credential]
[ValidateNotNullOrEmpty]
public PSCredential Credential
{
get { return _credential; }
set
{
_credential = value;
}
}
private PSCredential _credential;
public PSCredential Credential { get; set; }
/// <summary>
/// Specifies if Secured layer is required or not.
/// Gets or sets if Secured layer is required or not.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter UseSsl
{
get { return _usessl; }
set
{
_usessl = value;
}
}
private SwitchParameter _usessl;
public SwitchParameter UseSsl { get; set; }
/// <summary>
/// Specifies the Port to be used on the server. <see cref="SmtpServer"/>
/// Gets or sets the Port to be used on the server. <see cref="SmtpServer"/>
/// </summary>
/// <remarks>
/// Value must be greater than zero.
/// </remarks>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateRange(0, Int32.MaxValue)]
public int Port
{
get { return _port; }
set { _port = value; }
}
private int _port = 0;
public int Port { get; set; }
#endregion
#region private variables and methods
#region Private variables and methods
// Instantiate a new instance of MailMessage
private MailMessage _mMailMessage = new MailMessage();
@@ -282,7 +173,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
/// <param name="address"></param>
/// <param name="param"></param>
/// <returns></returns>
private void AddAddressesToMailMessage(object address, string param)
{
string[] objEmailAddresses = address as string[];
@@ -323,92 +213,90 @@ namespace Microsoft.PowerShell.Commands
#region Overrides
/// <summary>
/// ProcessRecord override.
/// BeginProcessing override.
/// </summary>
protected override
void
BeginProcessing()
protected override void BeginProcessing()
{
try
{
// Set the sender address of the mail message
_mMailMessage.From = new MailAddress(_from);
_mMailMessage.From = new MailAddress(From);
}
catch (FormatException e)
{
ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, _from);
ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, From);
ThrowTerminatingError(er);
// return;
}
// Set the recipient address of the mail message
AddAddressesToMailMessage(_to, "to");
AddAddressesToMailMessage(To, "to");
// Set the BCC address of the mail message
if (_bcc != null)
if (Bcc != null)
{
AddAddressesToMailMessage(_bcc, "bcc");
AddAddressesToMailMessage(Bcc, "bcc");
}
// Set the CC address of the mail message
if (_cc != null)
if (Cc != null)
{
AddAddressesToMailMessage(_cc, "cc");
AddAddressesToMailMessage(Cc, "cc");
}
//set the delivery notification
_mMailMessage.DeliveryNotificationOptions = _deliverynotification;
// Set the delivery notification
_mMailMessage.DeliveryNotificationOptions = DeliveryNotificationOption;
// Set the subject of the mail message
_mMailMessage.Subject = _subject;
_mMailMessage.Subject = Subject;
// Set the body of the mail message
_mMailMessage.Body = _body;
_mMailMessage.Body = Body;
//set the subject and body encoding
// Set the subject and body encoding
_mMailMessage.SubjectEncoding = Encoding;
_mMailMessage.BodyEncoding = Encoding;
// Set the format of the mail message body as HTML
_mMailMessage.IsBodyHtml = _bodyashtml;
_mMailMessage.IsBodyHtml = BodyAsHtml;
// Set the priority of the mail message to normal
_mMailMessage.Priority = _priority;
_mMailMessage.Priority = Priority;
//get the PowerShell environment variable
//globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer
// Get the PowerShell environment variable
// globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer
PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer);
if (_smtpserver == null && globalEmailServer != null)
if (SmtpServer == null && globalEmailServer != null)
{
_smtpserver = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture);
SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture);
}
if (string.IsNullOrEmpty(_smtpserver))
if (string.IsNullOrEmpty(SmtpServer))
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null);
this.ThrowTerminatingError(er);
}
if (_port == 0)
if (Port == 0)
{
_mSmtpClient = new SmtpClient(_smtpserver);
_mSmtpClient = new SmtpClient(SmtpServer);
}
else
{
_mSmtpClient = new SmtpClient(_smtpserver, _port);
_mSmtpClient = new SmtpClient(SmtpServer, Port);
}
if (_usessl)
if (UseSsl)
{
_mSmtpClient.EnableSsl = true;
}
if (_credential != null)
if (Credential != null)
{
_mSmtpClient.UseDefaultCredentials = false;
_mSmtpClient.Credentials = _credential.GetNetworkCredential();
_mSmtpClient.Credentials = Credential.GetNetworkCredential();
}
else if (!_usessl)
else if (!UseSsl)
{
_mSmtpClient.UseDefaultCredentials = true;
}
@@ -419,11 +307,11 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected override void ProcessRecord()
{
//add the attachments
if (_attachments != null)
// Add the attachments
if (Attachments != null)
{
string filepath = string.Empty;
foreach (string attachFile in _attachments)
foreach (string attachFile in Attachments)
{
try
{
@@ -431,9 +319,10 @@ namespace Microsoft.PowerShell.Commands
}
catch (ItemNotFoundException e)
{
//NOTE: This will throw
// NOTE: This will throw
PathUtils.ReportFileOpenFailure(this, filepath, e);
}
Attachment mailAttachment = new Attachment(filepath);
_mMailMessage.Attachments.Add(mailAttachment);
}
@@ -441,7 +330,7 @@ namespace Microsoft.PowerShell.Commands
}
/// <summary>
/// EndProcessing.
/// EndProcessing override.
/// </summary>
protected override void EndProcessing()
{
@@ -479,7 +368,7 @@ namespace Microsoft.PowerShell.Commands
WriteError(er);
}
//if we don't dispose the attachments, the sender can't modify or use the files sent.
// If we don't dispose the attachments, the sender can't modify or use the files sent.
_mMailMessage.Attachments.Dispose();
}