Reputation: 31
I'm trying to figure out how to get PowerShell V3 to send a message using gmail SMTP.
I have been researching for a whole day now and must be missing something, because I can't get past a timeout error...the current code is as follows, but I have tried many different code snippets all to no avail:
$sender = "[email protected]"
$recipient = "[email protected]"
$subject = "subject here"
$body = "test text here"
$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.Send($emsg);
When I run this I get:
Exception calling "Send" with "1" argument(s): "The operation has timed out."
At C:\Users\Tim\Desktop\Untitled8.ps1:13 char:1
+ $sc.Send($emsg);
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
So I tried using different 'send' statements and methods, like:
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Same thing - timeout errors...
So, tried switching off firewall and AV etc - no difference....so tried running Wireshark and Network Monitor - could not see a TLS handshake so assume this could be why it's timing out....setup gmail on Chrome on same machine and TLS handshake can be seen in the trace and sending emails works fine.
So, it's either user error :-) and I've done something mad - or something very strange going on?
Test environment is single Windows 7 Ultimate (fully patched and updated) -> switch -> router -> Internet (>20mbps)
Any help would be most appreciated, before I lose my grip on any remaining vestige of sanity. :-)
Upvotes: 0
Views: 1474
Reputation: 10107
Hmm..try using port 587:
$sc = new-object Net.Mail.SmtpClient("smtp.gmail.com", 587);
Upvotes: 2