可以在Java中使用MailDev吗?

huangapple go评论88阅读模式
英文:

Is it possible to use MailDev with Java?

问题

我在远程服务器上安装了一个MailDev实例。

我正在尝试理解是否可以使用Java(使用标准的JavaMailSender)向这个虚假的SMTP服务器发送电子邮件。

配置只需要URL和端口,但在我的情况下,它不起作用。

它始终返回:
邮件服务器连接失败;嵌套异常是com.sun.mail.util.MailConnectException: 无法连接到主机...

WebUI 正在正确运行,我可以在服务器上看到空的收件箱。

谢谢。

英文:

I have a MailDev instance installed on a remote Server.

I'm trying to understand if is it possibile to send email with Java (using the standard JavaMailSender) using this fake SMTP server.

The config needs only the URL and the port but, in my case, it doesn't work.

It returns always:
Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host ...

The WebUI is running correctly and I can see the empty inbox on server.

Thanks.

答案1

得分: 1

似乎你正在经历连接问题。虽然我无法告诉你导致问题的具体原因,但也许我可以提供一种替代解决方案来测试你的电子邮件?

使用 Wiser,你可以运行一个内嵌的 SMTP 服务器,并在你的 JUnit 测试中查询该服务器。我在我的开源项目 Simple Java Mail 中经常使用它,还为此创建了 一个 Rule

package testutil.testrules;

import org.jetbrains.annotations.NotNull;
import org.junit.rules.ExternalResource;
import org.subethamail.smtp.server.SMTPServer;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;

/**
 * SmtpServerRule - 一个包装 Wiser 实例的 TestRule(Java 中的 SMTP 服务器),在每个测试之前和之后启动和停止。
 * <br>
 * SmtpServerRule 公开了与 {@link Wiser} 实例相同的方法,通过将实现委托给该实例。但是,这些方法不能在 JUnit 语句之外使用(否则会引发 {@link IllegalStateException})。
 * <br>
 * 可以直接检索 {@link Wiser} 实例,但也只能从 JUnit 语句内部检索。
 */
public class SmtpServerRule extends ExternalResource {
    private final Wiser wiser = new Wiser();
    private final int port;

    public SmtpServerRule(@NotNull Integer port) {
        this.port = port;
    }

    @Override
    protected void before() {
        this.wiser.setPort(port);
        this.wiser.start();
    }

    @Override
    protected void after() {
        this.wiser.stop();
    }

    @NotNull
    public Wiser getWiser() {
        checkState("getWiser()");
        return this.wiser;
    }

    // 更多方法...
}

然后,我像这样使用它:

public class MailerLiveTest {
    private static final Integer SERVER_PORT = 251;

    @Rule
    public final SmtpServerRule smtpServerRule = new SmtpServerRule(SERVER_PORT);

    @Before
    public void setup() {
        mailer = MailerBuilder.withSMTPServer("localhost", SERVER_PORT).buildMailer();
    }

    @Test
    public void createMailSession_EmptySubjectAndBody() {
        // 使用 mailer 发送邮件,发送到 localhost:251

        MimeMessageAndEnvelope receivedMimeMessage = smtpServerRule.getOnlyMessage();
        Email receivedEmail = EmailConverter.mimeMessageToEmail(receivedMimeMessage.getMimeMessage());

        // 对 Email 对象执行断言...
    }
}
英文:

It seems like you are experience connections issues. Although I cannot tell you what the cause there is, perhaps I can offer an alternative solution to test your emails?

Using Wiser, you can run an embedded SMTP server and query that inside your junit test. I've used this a lot in my open source project Simple Java Mail and created a Rule for this:

package testutil.testrules;

import org.jetbrains.annotations.NotNull;
import org.junit.rules.ExternalResource;
import org.subethamail.smtp.server.SMTPServer;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;

/**
 * SmtpServerRule - a TestRule wrapping a Wiser instance (a SMTP server in Java), started and stopped right before and after each test.
 * &lt;br&gt;
 * SmtpServerRule exposes the same methods as the {@link Wiser} instance by delegating the implementation to the instance. These methods, however, can not be
 * used outside a JUnit statement (otherwise an {@link IllegalStateException} is raised).
 * &lt;br&gt;
 * The {@link Wiser} instance can be directly retrieved but also only from inside a JUnit statement.
 */
public class SmtpServerRule extends ExternalResource {
	private final Wiser wiser = new Wiser();
	private final int port;

	public SmtpServerRule(@NotNull Integer port) {
		this.port = port;
	}

	@Override
	protected void before() {
		this.wiser.setPort(port);
		this.wiser.start();
	}

	@Override
	protected void after() {
		this.wiser.stop();
	}

	@NotNull
	public Wiser getWiser() {
		checkState(&quot;getWiser()&quot;);
		return this.wiser;
	}

	@NotNull
	public List&lt;WiserMessage&gt; getMessages() {
		checkState(&quot;getMessages()&quot;);
		return wiser.getMessages();
	}
	
	@NotNull
	public MimeMessage getOnlyMessage(String envelopeReceiver)
			throws MessagingException {
		checkState(&quot;getMessages()&quot;);
		List&lt;WiserMessage&gt; messages = getMessages();
		assertThat(messages).hasSize(1);
		Iterator&lt;WiserMessage&gt; iterator = messages.iterator();
		WiserMessage wiserMessage = iterator.next();
		assertThat(wiserMessage.getEnvelopeReceiver()).isEqualTo(envelopeReceiver);
		MimeMessage mimeMessage = wiserMessage.getMimeMessage();
		iterator.remove();
		return mimeMessage;
	}
	
	@NotNull
	public MimeMessageAndEnvelope getOnlyMessage()
			throws MessagingException {
		checkState(&quot;getMessages()&quot;);
		List&lt;WiserMessage&gt; messages = getMessages();
		assertThat(messages).hasSize(1);
		Iterator&lt;WiserMessage&gt; iterator = messages.iterator();
		WiserMessage wiserMessage = iterator.next();
		iterator.remove();
		return new MimeMessageAndEnvelope(wiserMessage.getMimeMessage(), wiserMessage.getEnvelopeSender());
	}
	
	@NotNull
	public MimeMessage getMessage(String envelopeReceiver)
			throws MessagingException {
		checkState(&quot;getMessages()&quot;);
		List&lt;WiserMessage&gt; messages = getMessages();
		Iterator&lt;WiserMessage&gt; iterator = messages.iterator();
		while (iterator.hasNext()) {
			WiserMessage wiserMessage = iterator.next();
			if (wiserMessage.getEnvelopeReceiver().equals(envelopeReceiver)) {
				MimeMessage mimeMessage = wiserMessage.getMimeMessage();
				iterator.remove();
				return mimeMessage;
			}
		}
		throw new AssertionError(&quot;message not found for recipient &quot; + envelopeReceiver);
	}

	@NotNull
	public SMTPServer getServer() {
		checkState(&quot;getServer()&quot;);
		return wiser.getServer();
	}

	public boolean accept(String from, String recipient) {
		checkState(&quot;accept(String, String)&quot;);
		return wiser.accept(from, recipient);
	}

	public void deliver(String from, String recipient, InputStream data)
			throws IOException {
		checkState(&quot;deliver(String, String, InputStream)&quot;);
		wiser.deliver(from, recipient, data);
	}

	public void dumpMessages(PrintStream out)
			throws MessagingException {
		checkState(&quot;dumpMessages(PrintStream)&quot;);
		wiser.dumpMessages(out);
	}

	private void checkState(String method) {
		if (this.wiser == null) {
			throw new IllegalStateException(format(&quot;%s must not be called outside of a JUnit statement&quot;, method));
		}
	}
}

Then I use it like this:

public class MailerLiveTest {
	private static final Integer SERVER_PORT = 251;

	@Rule
	public final SmtpServerRule smtpServerRule = new SmtpServerRule(SERVER_PORT);

	@Before
	public void setup() {
		mailer = MailerBuilder.withSMTPServer(&quot;localhost&quot;, SERVER_PORT).buildMailer();
	}
	
	@Test
	public void createMailSession_EmptySubjectAndBody() {
		// send mail using mailer, which goes to localhost:251

		MimeMessageAndEnvelope receivedMimeMessage = smtpServerRule.getOnlyMessage();
		Email receivedEmail = EmailConverter.mimeMessageToEmail(receivedMimeMessage.getMimeMessage());

		// perform assertions on Email object...
	}
}

答案2

得分: 0

检查mail.smtp.auth和mail.smtp.starttls.enable是否设置为false。 在我的情况下,这样做有效(我还将localhost设置为主机,端口设置为1025)。

英文:

Check if mail.smtp.auth and mail.smtp.starttls.enable are set to false. In my case it worked (I also set localhost as host and 1025 as port).

huangapple
  • 本文由 发表于 2020年9月30日 16:59:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64134221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定