SMTPSecureSocket Problem

So our company has decided to eliminate our internal SMTP server and move mail relay to a service called SendGrid which means I have to modify all my internal apps to use this service to end out error emails. I’m pulling my hair out because I cannot get it to work. It is supposed to work with no encryption on port 587 and that appears to be the case with the VB code one of my coworkers has tested but it is not working in Xojo.
Here is the SendGrid relevant documentation page :
This is the VB code that is working:

[code]Sub Main()
Using mail As New System.Net.Mail.MailMessage
mail.From = New System.Net.Mail.MailAddress(“do_not_reply@company.com”)
mail.To.Add(“user.name@company.com”)
mail.Subject = “New SMTP Test”
mail.Body = “This is a test.”

        Using smtp As New System.Net.Mail.SmtpClient("smtp.sendgrid.net", 587)
            smtp.UseDefaultCredentials = False
            smtp.Credentials = New System.Net.NetworkCredential("username", "password")
            Try
                smtp.Send(mail)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Using
    End Using
End Sub

[/code]

Here is the equivalent code I’m using:

[code]MailSocket As SMTPSecureSocket
Sub ConnectionEstablished(greeting as string) Handles ConnectionEstablished
Window1.TextArea1.Text = Greeting
End Sub
Sub MailSent() Handles MailSent
MsgBox(“Mail sent.”)
End Sub
Sub ServerError(ErrorID as integer, ErrorMessage as string, Email as EmailMessage) Handles ServerError
MsgBox(“There was an error sending the email. ErrorID=” + Str(ErrorID) + ", " + ErrorMessage)
Window1.TextArea1.Text = Window1.TextArea1.Text + EndOfLine + ErrorMessage
End Sub

SendButton As PushButton
Sub Action() Handles Action
// Connect to SendGrid
MailSocket.Address = “smtp.sendgrid.net
MailSocket.Port = 587
MailSocket.Username = “username”
MailSocket.Password = “password”
// Create EmailMessage
Dim mail As New EmailMessage
mail.FromAddress = “noreply@company.com
mail.AddRecipient(ToField.Text)
mail.Subject = SubjectField.Text
mail.BodyPlainText = MessageArea.Text
mail.Headers.AppendHeader(“X-Mailer”,“SMTP Test”)
// Send it
MailSocket.Messages.Append(mail)
MailSocket.SendMail
End Sub[/code]

This always generates the following ConnectionEstablished and ServerError output and the email message doesn’t get sent:

[quote]SG ESMTP service ready at ismtpd0091p1mdw1.sendgrid.net
535 Authentication failed: The provided authorization grant is invalid, expired, or revoked[/quote]

The authentication fails regardless of whether I use the code above or add TLS encryption. I’ve also tried a SSL connection but with that I get no ConnectionEstablished feedback and it isn’t working at all . Everything I try from searching examples fails. Does anyone have any advice? I don’t have a way to contact SendGrid directly because the master account is in someone else’s name. I have only been provided with a username and password to send mail with and that is the same as the one that is working with the VB code.

Note, I can successfully send to our still functioning SMTP server without a login on port 25 so something else is going on with the login that is different from Xojo to VB.

To avoid problems if/when port is different from 587 I use this snippet:

if SMTPSock.port = 587 then
SMTPsock.SMTPConnectionMode = 0
else//465
SMTPsock.SMTPConnectionMode = 1
end if
SMTPsock.ConnectionType = SSLSocket.SSLv23//ot whatever

Hope it helps.

465 is the correct port for Sendgrid.

Unfortunately 465 is not working for me which means either my code is wrong or there is an issue with SMTPSecureSocket working with SendGrid.

Nope, working fine here. Both with SMTPSecureSocket and the Chilkat plugin.

[code]// set up the socket
Socket1.SSLEnabled = True
Socket1.SSLConnectionType = SSLSocket.SSLConnectionTypes.TLSv1
Socket1.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
socket1.address = “smtp.sendgrid.net
socket1.port = 465
socket1.username = GetMore
socket1.password = GetSocket

// populate the email message
dim mail as new emailMessage
mail.fromAddress = GetMore
mail.subject = “Request for Trial Extension”
mail.bodyPlainText = "Username: " + STUserName.Value + CarbonModule.EndOfLineMacintosh + "Email Address: " + EFEmailAddress.Value
mail.headers.AddHeader(“X-Mailer”, app.getMyAppName)
// add recipients
mail.AddRecipient GetMore
// send the email
socket1.messages.AddRow mail
socket1.sendMail[/code]

I get this error #103, Unable to resolve address. I get the same error trying to send to smtp.gmail .com.
DNS resolves smtp.sendgrid.net so I don’t know what address the code is trying to resolve that it can’t.

F:\>nslookup smtp.sendgrid.net
Server: clkswjpdc02.jostens.com
Address: 167.237.64.7

Non-authoritative answer:
Name: smtp.sendgrid.net
Addresses: 169.47.148.173
167.89.115.18
169.47.155.6
169.47.148.162
167.89.123.53
167.89.115.53
167.89.123.58
167.89.115.79
167.89.123.82

[code]// Connect to SendGrid
MailSocket.SSLEnabled = True
MailSocket.ConnectionType = SMTPSecureSocket.TLSv1
MailSocket.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
MailSocket.Address = “smtp.sendgrid.net
MailSocket.Port = 465
MailSocket.Secure = True

MailSocket.Username = “username”
MailSocket.Password = “password”

// Create EmailMessage
Dim mail As New EmailMessage
mail.FromAddress = “noreply@jostens.com
mail.AddRecipient(ToField.Text)
mail.Subject = SubjectField.Text
mail.BodyPlainText = MessageArea.Text
mail.Headers.AppendHeader(“X-Mailer”,“SMTP Test”)

// Send it
MailSocket.Messages.Append(mail)
MailSocket.SendMail
[/code]

Same error 103 with this code too

[code]// Connect to SendGrid
MailSocket.SSLEnabled = True
MailSocket.SSLConnectionType = SSLSocket.SSLConnectionTypes.TLSv1
MailSocket.SMTPConnectionMode = SMTPSecureSocket.ModeSSLTLS
MailSocket.Address = “smtp.sendgrid.net
MailSocket.Port = 465
MailSocket.Secure = True

MailSocket.Username = “username”
MailSocket.Password = “password”

// Create EmailMessage
Dim mail As New EmailMessage
mail.FromAddress = “noreply@jostens.com
mail.AddRecipient(ToField.Text)
mail.Subject = SubjectField.Text
mail.BodyPlainText = MessageArea.Text
mail.Headers.AppendHeader(“X-Mailer”,“SMTP Test”)

// Send it
MailSocket.Messages.Append(mail)
MailSocket.SendMail[/code]

Ahem, did you do the needful - meaning did you satisfy our nanny Apple? I think it’s NSAllowsArbitraryLoads = yes. Otherwise, your code looks identical to mine.

Nanny Apple? On a Dell Windows 10 Laptop? Nope.

did you copy and paste the host? If so try to remove the entire string and retype it in the ide

Or Flushdns on windows may help

I just did both before trying again, Flushed the DNS cache and retyped “smtp.sendgrid.net”. Same result. The SMTPSecureSocket Error event generates a 103 error, Unable to resolve address.

Have you tried to use CURL from the MBS plugin? The plugin has a debug mode that gives better errors. The Chilkat plugin does the same. There you can at least see if the problem is on your side or not.

Your mx record @jostens.com gives mimecast as the provider is that correct?

I believe that is correct as of now.

OK here is the Chilikat Log:

ChilkatLog: SendEmail: DllDate: Oct 28 2019 ChilkatVersion: 9.5.0.80 UnlockPrefix: anything for 30 day trial Architecture: Little Endian; 32-bit Language: Windows Xojo VerboseLogging: 0 sendEmailInner: renderToMime_pt1: createEmailForSending: Auto-generating Message-ID --createEmailForSending --renderToMime_pt1 sendMimeInner: ensureSmtpSession: ensureSmtpConnection: smtpParams: SmtpHost: smtp.sendgrid.net SmtpPort: 465 SmtpUsername: apikey SmtpSsl: 1 StartTLS: 0 --smtpParams smtpConnect: smtpHostname: smtp.sendgrid.net smtpPort: 465 connectionIsReady: Need new SMTP connection --connectionIsReady smtpSocketConnect: socket2Connect: connect2: connectImplicitSsl: connectSocket: connect_ipv6_or_ipv4: Connection attempt failed. maxWaitTimeMs: 30000 totalMsWaitedSoFar: 950 --connect_ipv6_or_ipv4 --connectSocket --connectImplicitSsl ConnectFailReason: Connection rejected A few possible causes for a connection being rejected are: - A firewall (software or hardware), such as Windows Firewall, is blocking the connection . - Nothing is listening at the remote host:port --connect2 --socket2Connect Failed to connect to SMTP server.. --smtpSocketConnect --smtpConnect --ensureSmtpConnection --ensureSmtpSession --sendMimeInner --sendEmailInner Failed. --SendEmail --ChilkatLog

This indicates to me that the error I’m getting with 587 - “535 Authentication failed: The provided authorization grant is invalid, expired, or revoked” may be the same thing happening with SSL on 465. I have tried the two different apikey passwords provided to me and I’m getting this response on both of them.

However Chilikat was successful changing mailman.SmtpPort = 587 and mailman.SmtpSsl = false
I received the email for that try. This is at least encouraging that the credentials passed authentication. Why that is failing on port 465 is a mystery unless the corporate firewall is blocking that outgoing port.

ChilkatLog: SendEmail: DllDate: Oct 28 2019 ChilkatVersion: 9.5.0.80 UnlockPrefix: anything for 30 day trial Architecture: Little Endian; 32-bit Language: Windows Xojo VerboseLogging: 0 sendEmailInner: renderToMime_pt1: createEmailForSending: Auto-generating Message-ID --createEmailForSending --renderToMime_pt1 sendMimeInner: ensureSmtpSession: ensureSmtpConnection: smtpParams: SmtpHost: smtp.sendgrid.net SmtpPort: 587 SmtpUsername: apikey SmtpSsl: 0 StartTLS: 0 --smtpParams smtpConnect: smtpHostname: smtp.sendgrid.net smtpPort: 587 connectionIsReady: Need new SMTP connection --connectionIsReady smtpSocketConnect: socketOptions: SO_SNDBUF: 262144 SO_RCVBUF: 4194304 TCP_NODELAY: 1 SO_KEEPALIVE: 1 --socketOptions --smtpSocketConnect smtpGreeting: readSmtpResponse: SmtpCmdResp: 220 SG ESMTP service ready at ismtpd0061p1iad1.sendgrid.net --readSmtpResponse --smtpGreeting ehloCommand: sendCmdToSmtp: SmtpCmdSent: EHLO CLKWWNFWXD2Z2<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 250-smtp.sendgrid.net SmtpCmdResp: 250-8BITMIME SmtpCmdResp: 250-PIPELINING SmtpCmdResp: 250-SIZE 31457280 SmtpCmdResp: 250-STARTTLS SmtpCmdResp: 250-AUTH PLAIN LOGIN SmtpCmdResp: 250 AUTH=PLAIN LOGIN --readSmtpResponse --ehloCommand This SMTP server supports STARTTLS. Automatically doing STARTTLS... startTLS: sendCmdToSmtp: SmtpCmdSent: STARTTLS<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 220 Begin TLS negotiation now --readSmtpResponse TLS connection established. --startTLS ehloCommand: sendCmdToSmtp: SmtpCmdSent: EHLO CLKWWNFWXD2Z2<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 250-smtp.sendgrid.net SmtpCmdResp: 250-8BITMIME SmtpCmdResp: 250-PIPELINING SmtpCmdResp: 250-SIZE 31457280 SmtpCmdResp: 250-STARTTLS SmtpCmdResp: 250-AUTH PLAIN LOGIN SmtpCmdResp: 250 AUTH=PLAIN LOGIN --readSmtpResponse --ehloCommand --smtpConnect --ensureSmtpConnection ensureSmtpAuthenticated: smtpAuthenticate: smtp_host: smtp.sendgrid.net smtp_port: 587 smtp_user: apikey smtpAuthenticate: login_method: LOGIN auth_login: smtpSendGet2: sendCmdToSmtp: SmtpCmdSent: AUTH LOGIN<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 334 VXNlcm5hbWU6 --readSmtpResponse --smtpSendGet2 sendCmdToSmtp: SmtpCmdSent: YXBpa2V5<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 334 UGFzc3dvcmQ6 --readSmtpResponse sendCmdToSmtp: SmtpCmdSent: {PasswordOrCredentials} --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 235 Authentication successful --readSmtpResponse --auth_login --smtpAuthenticate ConnectionType: SSL/TLS --smtpAuthenticate --ensureSmtpAuthenticated --ensureSmtpSession sendSmtpEmail: sendWithPipelining: sendMailFrom: mailFrom: noreply@jostens.com sendCmdToSmtp: SmtpCmdSent: MAIL FROM:<noreply@jostens.com><CRLF> --sendCmdToSmtp --sendMailFrom sendRcptTo: sendCmdToSmtp: SmtpCmdSent: RCPT TO:<tom.dixon@jostens.com><CRLF> --sendCmdToSmtp --sendRcptTo sendCmdToSmtp: SmtpCmdSent: DATA<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 250 Sender address accepted --readSmtpResponse readRcptTo: readSmtpResponse: SmtpCmdResp: 250 Recipient address accepted --readSmtpResponse recipient: tom.dixon@jostens.com --readRcptTo readSmtpResponse: SmtpCmdResp: 354 Continue --readSmtpResponse --sendWithPipelining sendCmdToSmtp: SmtpCmdSent: <CRLF>.<CRLF> --sendCmdToSmtp readSmtpResponse: SmtpCmdResp: 250 Ok: queued as EwZOas7DR7KgPQuVuu9luw --readSmtpResponse --sendSmtpEmail --sendMimeInner --sendEmailInner Success. --SendEmail --ChilkatLog \\r\ Sent!

You sure the firewall Or antivirus is not blocking?

1 Like

It is entirely possible that the firewall is blocking outgoing 465 but it is definitely not blocking 587. If I can get SMTPSecureSocket working on port 587 I don’t care if they are currently blocking 465. However I’m back to where I started. SMTPSecureSocket is not authenticating. ChiliKat can authenticate so there is something either not functioning correctly in 2019R2.1 SMTPSecreSocket or I’m missing something in my code.

I’ve tested the same socket lately it worked fine, so it could be more something in the dns perhaps. Tried it on macos or linux?

It won’t mater to me if it works on MacOS or Linux. Virtually all my apps run as stand-alone Web app on Windows servers. I’m checking with our firewall guys regarding whether port 465 is blocked or not but regardless whether it is it doesn’t explain why the Chilikat plugin using port 587 works but SMTPSecureSocket doesn’t work. If push comes to shove I can always buy a Chilikat license but I really should not have to since SMTPSecureSocket should just work.