1

Need to send email via private smtp server with credential and starttls. I read many tutorials and still cannot establish starttls communication.

My code:

 $smtpServer = "smtp.xserver.cz"

 #Creating a Mail object
 $msg = new-object Net.Mail.MailMessage

 #Creating SMTP server object
 $smtp = new-object Net.Mail.SmtpClient($smtpServer, 25)#587 works
 $smtp.EnableSsl = $false
 $smtp.Credentials = New-Object System.Net.NetworkCredential("myuser@xserver.cz","mypassword"); #yes, correct login, tried via Thunderbird


 #Email structure 
 $msg.From = "info@xserver.cz"
 $msg.To.Add("testtest@gmail.com")

 $msg.subject = "subject"


 $msg.IsBodyHTML = $true
 $msg.body = "AAA"+"<br /><br />"

 $ok=$true
 try{
        $smtp.Send($msg)
        Write-Host "SENT"

 }
 catch {
    Write-Host "`tNOT WORK !!!!!"
    $error[0]
    $_.Exception.Response
    $ok=$false
 }
 finally{
    $msg.Dispose()

 }
 if($ok){
    Write-Host "`tEVERYTHING OK"
 }

Need to use .Net objects and class, not third party library, or Send-MailMessage in Powershell, because Send-MailMessage doesn't have atachment sending options.

user3592226
  • 11
  • 1
  • 1
  • 2

1 Answers1

1

You're not getting your TLS connect because you've set EnableSsl to $false.

Not sure where you got the idea that Send-MailMessage doesn't have attachment sending options. Sending attachments with Send-MailMailMessage is ridiculously easy. It accepts one or more file names to use as attachments from the pipeline, or through the -Attachments parameter.

mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • I also tried enableSSL to true, but not sure, which port used... Please help me with code. Sorry, my mistake - Send-MailMessage is not acceptable due to send Credentials to my private smtp server. – user3592226 May 11 '14 at 14:41
  • Usually TLS is implemented on the same port (25), or on 587. Send-MailMessage also has a -Credential parameter. – mjolinor May 11 '14 at 14:56
  • I tried 25 and 587, nothing works. Yes, -Credentials parameters is there, but it is credential for running script on Windows, not for server's remote connection. – user3592226 May 11 '14 at 15:04
  • See this thread: http://stackoverflow.com/questions/12460950/how-to-pass-credentials-to-the-send-mailmessage-command-for-sending-emails As for the TLS, the port for that will be configured on the mail server, so I can't tell you what it is (and whether it even supports TLS). – mjolinor May 11 '14 at 19:14
  • I tried my login via Thunderbird. With configuration noTLS on smtp, there was error with outgoing emails. But when I set StartTLS, everything works. So, there I can see port 25, StartTLS configuration, but still cannot establish connection throught Powershell. I also tried PhpMailer library. How is it possible, that Thudenrbird can send email and my script no? – user3592226 May 11 '14 at 21:03