문제
Java에서 SMTP 메시지를 어떻게 보내나요?
해결책
다음은 Gmail smtp의 예입니다.
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail@tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen@iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin@tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
이제 프로젝트 종속성을 최소로 유지하려는 경우에만 이 방법을 수행하십시오. 그렇지 않으면 아파치의 클래스를 사용하는 것이 좋습니다.
http://commons.apache.org/email/
문안 인사
토브 아르 야콥센
다른 팁
또 다른 방법은 아스피린(https://github.com/masukomi/aspirin) 이와 같이:
MailQue.queMail(MimeMessage message)
..위와 같이 MIME 메시지를 구성한 후.
아스피린 ~이다 smtp '서버'이므로 구성할 필요가 없습니다.그러나 메일 서버와 클라이언트 애플리케이션을 수신하는 데에는 다양한 스팸 필터링 규칙이 적용되기 때문에 광범위한 수신자에게 이메일을 보내는 것은 보이는 것만큼 간단하지 않습니다.
이 게시물을 참조하십시오
GMail, Yahoo 또는 Hotmail을 사용하여 Java 애플리케이션으로 이메일을 보내려면 어떻게 해야 합니까?
Gmail에만 해당되지만 smtp 자격 증명을 대체할 수 있습니다.
참조 자바메일 API 및 관련 javadoc.
Java Practices의 다음 튜토리얼을 참조하세요.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
제휴하지 않습니다 StackOverflow