简体   繁体   中英

Powershell timeout when sending email

I am trying to send a mail using powershell by making use of gmail smtp server. Here's my code snippet.

$sender = "user1@domain.com"
$recipient = "user2@domain.com"
$subject = "test"
$body = "test text"
$username = "user1@domain.com"
$password = "password"

$sc = new-object Net.Mail.SmtpClient("smtp.gmail.com", 465);
$sc.EnableSsl = $true;
$cred = New-Object System.Net.NetworkCredential($username,$password);
$sc.Credentials = $cred;
$emsg = new-Object System.Net.Mail.MailMessage($sender, $recipient, $subject, $body);
$sc.Timeout = 180000
$sc.Send($emsg);

Everytime I recieve a timeout, even if I have fixed the timeout value to 3 minutes(180 seconds). To be more precise, the error is

Exception calling "Send" with "1" argument(s): "The operation has timed out."
At line:15 char:1
+ $sc.Send($emsg);
+ ~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException

Have anyone experienced this issue before? Any suggestions or ideas would be really appreciated.

Posting that it could save someone's time too..

$param = @{
SmtpServer = 'smtp.gmail.com'
Port = 587
UseSsl = $true
Credential  = 'user1@domain.com'
From = 'user1@domain.com'
To = 'user2@domain.com'
Subject = 'test'
Body = "testtext"
}
Send-MailMessage @param

PS here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM