Amessihel
Amessihel

Reputation: 6384

SmtpClient Class: send() works but not sendAsync()

I'm writing a simple Windows Form (Visual Studio 2010, .NET 4.0, Windows 2008 32bit). Clicking on a button make send an e-mail.

The function SendMaildButton_Click() sends the mail, and if completed (aSync method), it calls SendCompletedCallback().

Public Class MailForm
    Private sc As System.Net.Mail.SmtpClient

    Private Sub MailForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        sc = New System.Net.Mail.SmtpClient
        AddHandler sc.SendCompleted, AddressOf SendCompletedCallback
    End Sub

    Private Sub SendCompletedCallback(ByVal sender As Object, _
                                      ByVal e As AsyncCompletedEventArgs)
        ' [...]
    End Sub

    Private Sub SendMaildButton_Click(ByVal sender As System.Object, _
                                      ByVal e As System.EventArgs) Handles SendButton.Click
        'sc instance of SmtpClient already created on OnLoad form event
        ' [sc.Host, sc.Port, sc.Credentials stuff ...]

        Dim message As MailMessage
        ' [message filling]

        ' [relevant part : Send or SendAsync]

        ' freedom...
        message.Dispose()
    End Sub
End Class

This works perflectly if the sending code is :

sc.Send()

Event fakeSMTPServer (a dummy smtp server) or Gmail get it. When I rather use :

Dim userState As String = "plap" 'message.GetHashCode
AddHandler sc.SendCompleted, AddressOf SendCompletedCallback
sc.SendAsync(message, userState)

It doesn't work... fakeSMTPServer notify a mail reception, but without genuinely retrieving it.
The message error is : "Failure sending mail"

Here's the stacktrace of fakeSMTPServer:

19 janv. 2017 17:15:43 ERROR com.nilhcem.fakesmtp.server.MailSaver -
java.io.EOFException: Pre-mature end of <CRLF>.<CRLF> terminated data
        at org.subethamail.smtp.io.DotTerminatedInputStream.read(DotTerminatedInputStream.java:73) ~[fakeSMTP-2.0.jar:na]
        at org.subethamail.smtp.io.DotUnstuffingInputStream.read(DotUnstuffingInputStream.java:47) ~[fakeSMTP-2.0.jar:na]
        at org.subethamail.smtp.io.DotUnstuffingInputStream.read(DotUnstuffingInputStream.java:76) ~[fakeSMTP-2.0.jar:na]

What dit I miss?

Upvotes: 1

Views: 463

Answers (1)

VMAtm
VMAtm

Reputation: 28355

The problem is in here:

message.Dispose()

You're freeing your resources before email is sent. You should free your resources only in the SendCompletedCallback, because right now you simply say: start sending this… oh, no, never mind.

Upvotes: 1

Related Questions