Java Tutorial/Email/Introduction
Java Mail Development Environment
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MainClass {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.host", "mail.cloud9.net");
Session mailConnection = Session.getInstance(props, null);
Message msg = new MimeMessage(mailConnection);
Address a = new InternetAddress("a@a.ru", "A a");
Address b = new InternetAddress("fake@jexp.ru");
msg.setContent("Mail contect", "text/plain");
msg.setFrom(a);
msg.setRecipient(Message.RecipientType.TO, b);
msg.setSubject("subject");
Transport.send(msg);
}
}
Send an email message
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
String from = "user@some-domain.ru";
String to = "user@some-domain.ru";
String subject = "Hi There...";
String text = "How are you?";
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.some-domain.ru");
properties.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(properties, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
}
Send E-Mail
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendApp {
public static void send(String smtpHost, int smtpPort, String from, String to, String subject,
String content) throws AddressException, MessagingException {
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "" + smtpPort);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
send("hostname", 25, "j@s.ru", "s@s.ru", "re: dinner", "body");
}
}