API VB.NET SmtpClient ограничен по сравнению с Java SendMail? - PullRequest
0 голосов
/ 18 апреля 2019

Я создал способ отправки электронной почты в VB.NET:

Imports System.Threading
Imports System.Net.Mail
Imports System.ComponentModel

Module Module1
    Dim smtpList As New ArrayList

    Dim counter = 0

    Private Sub smtpClient_SendCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
        System.Diagnostics.Debug.WriteLine("completed!")
        System.Console.WriteLine("completed!")
    End Sub

    Public Function createSmtp() As SmtpClient
        Dim smtp = New SmtpClient()
        Dim user = "AKAKAKAKAKAKAKAK"
        Dim host = "smtp.mailgun.org"
        Dim pass = "akakakakakakakakakakakakakakakakakakakak"

        smtp.Host = host
        smtp.Port = 587
        smtp.Credentials = New System.Net.NetworkCredential(user, pass)
        smtp.EnableSsl = True

        Return smtp
    End Function

    Public Sub SendEmail(email As String, bodystuff As String, smtp As SmtpClient)


        Dim from As New MailAddress("contat@testsitetetete.com", "Info", System.Text.Encoding.UTF8)
        Dim [to] As New MailAddress(email)
        Dim message As New MailMessage(from, [to])
        message.Body = String.Format("The message I want to send is to this <b>contact: {0}{1}</b>", vbCrLf, bodystuff)
        message.IsBodyHtml = True
        message.BodyEncoding = System.Text.Encoding.UTF8
        message.Subject = "Test email subject"
        message.SubjectEncoding = System.Text.Encoding.UTF8
        message.Priority = MailPriority.High


        ' Set the method that is called back when the send operation ends.
        AddHandler smtp.SendCompleted, AddressOf smtpClient_SendCompleted

        smtp.Send(message)
        'smtp.SendMailAsync(message)

        counter = counter + 1 ' I know its not thread safe, just to get a counter

        System.Console.WriteLine("Counter -> " & counter)

    End Sub


    Public Sub StartEmailRun()
        System.Diagnostics.Debug.WriteLine("StartEmailRun")

        'Dim smtp = createSmtp()

        Try
            For i = 0 To 8

                Dim thread As New Thread(
                  Sub()
                      Dim smtp = createSmtp()
                      SendEmail("someamail@testemail.com", "email test", createSmtp())
                  End Sub
                )
                thread.Start()
            Next

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub Main()
        System.Diagnostics.Debug.WriteLine("Starting the email sending...")

        ThreadPool.SetMinThreads(100, 100) ' just to make sure no thread pool issue or limitation

        createSmtp()

        StartEmailRun()

        Thread.Sleep(300000) ' make the program alive
    End Sub

End Module

и я создал этот же метод в Java:

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class TestMail 
{

    public static void main(String[] args) throws AddressException, MessagingException, InterruptedException 
    {

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", true);
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", "smtp.mailgun.org");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.ssl.trust", "smtp.mailgun.org");

        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String username = "akakakakakakakakakak";
                String password = "kajdfkjasfkjasdfksjdfksdajfksdfjsdkfjdskfjkW";
                return new PasswordAuthentication(username, password);
            }
        });


        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("testacount@test.com"));
        message.setRecipients(
          Message.RecipientType.TO, InternetAddress.parse("atest@test.com"));
        message.setSubject("Mail Subject");

        String msg = "This is my first email using JavaMailer";

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(msg, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        message.setContent(multipart);
        for (int i = 0; i < 8; i++) 
        {
            new Thread(new Runnable() {

                public void run() {
                    try {
                        Transport.send(message);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }   
                    System.out.println("sent...");
                }
            }).start();
        }

        while(true)
        {
            Thread.sleep(1000);
        }
    }
}

Я ожидал, что код VB.NET отправит электронные письма одновременно, как это делает java.

Но отправленное электронное письмо выглядит последовательным. В Java все письма отправляются одновременно.

Я думаю, что есть несколько ограничений на отправку нескольких электронных писем в коде VB.Net.

Есть ли способ отправить несколько электронных писем одновременно в VB.NET???

p.s. не говорю о bbc, потому что каждое письмо отличается от другого.

...