I am a new user of javax mail API. (javax.mail.*)
By trying out vanilla examples, it seems I can send out email from any address without authentication by setting the address using setFrom()
I tried this out on enterprise mail server and it works without warning.
This contradicts with my common sense that one need to login email account and then send out email from there.
Is this a commonly expected behavior of javax mail API and email server?
This is the code I used.
import java.io.UnsupportedEncodingException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class EmailTest {
JavaMailSenderImpl mailSender;
MimeMessage message;
MimeMessageHelper helper;
@Before
public void setUp() {
mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.company.com" ); //<some smtp host>
message = mailSender.createMimeMessage();
helper = new MimeMessageHelper(message);
}
@Test
public void sendEmail() {
try {
helper.setFrom("john@company.com", "john doe");
helper.setTo("jane@company.com");
helper.setSubject("test subject");
helper.setText("Test Text");
mailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
This is not specific to Java. A sender address in a mail is just a field you can fill arbitrarily, no matter the technology. However, many mail servers will reject emails that you are trying to send without using your own email. Email servers that indeed allow any sender address will require some other kind of authentication
EDIT: compare to letters. When sending an old school letter (aka snail mail) you can put any address as the sender. the post office does not care as long as you pay for its delivery. In exactly the same way, the mail servers often do not care.
EDIT 2: however, you might run into legal problems if you try to impersonate or mislead someone. When you put Donald Duck as a sender, no one will care. If you put Donald Trump on it as sender, you might get sued for more money than you can imagine. This is true for snail mail and e mail.