Sending Authenticated E-mail using .NET

The following code shows how to send an e-mail using the .NET System.Mail namespace. The code is written for APLX (discontinued in 2016), but can also be used with Dyalog after some modifications.

The example shows how to contact an SMTP mail server which requires authentication - i.e. requires you to provide a user name and password when the SMTP connection is established. This is an increasingly common requirement designed to combat anonymous Spam e-mails.

Depending on the SMTP server you are using, you may need to make some small changes to the code:


⍝ Example of sending an E-Mail message using .NET
⍝ See
⍝ Create a test message
message←'.net' ⎕NEW 'System.Net.Mail.MailMessage' from to
message.Subject←'Pricing and Availability'
message.Body←'Did you get the new price list?',⎕R,'Thanks. Bob'
⍝ Create an SMTP client
⍝ (You may need to change the port number)
smtpClient←'.net' ⎕NEW 'System.Net.Mail.SmtpClient'
⍝ Set login credentials used to authenticate us to the SMTP server
⍝ (If your SMTP server doesn't use authentication, omit this bit)
credentials←'.net' ⎕NEW 'System.Net.NetworkCredential'

⍝ Note: The order of these two lines seems to matter
⍝ If they are reversed, may get a .NET exception:
⍝     System.Net.Mail.SmtpException: The SMTP server requires 
⍝     a secure connection or the client was not authenticated. 
⍝     The server response was: 5.5.1 Authentication Required

⍝ Use SSL for secure connection
⍝ (If your SMTP server doesn't use SSL, omit this bit)
⍝ Send the message
smtpClient.Send message

Author: SimonMarsden

CategoryDotNet CategoryEmail

AuthenticatedEmail (last edited 2017-02-16 19:40:56 by KaiJaeger)