· 7 years ago · Oct 19, 2018, 02:52 PM
1import java.util.Properties;
2import javax.mail.Message;
3import javax.mail.Session;
4import javax.mail.Transport;
5import javax.mail.internet.InternetAddress;
6import javax.mail.internet.MimeMessage;
7
8public class Tester {
9
10 private static String USER_NAME = "someemail@yahoo.com"; // Yahoo user name (just the part before "@gmail.com")
11 private static String PASSWORD = "test"; // Yahoo password
12 private static String RECIPIENT = "someemail@otheremail.com";
13
14 public static void main(String[] args) {
15 String from = USER_NAME;
16 String pass = PASSWORD;
17 String[] to = { RECIPIENT }; // list of recipient email addresses
18 String subject = "Java send mail example";
19 String body = "Welcome to JavaMail!";
20
21 sendFromGMail(from, pass, to, subject, body);
22 }
23
24 private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
25 Properties props = System.getProperties();
26 String host = "smtwewep.mail.yahoo.com";
27 props.put("mail.smtp.starttls.enable", "true");
28 props.put("mail.smtps.host", host);
29 props.put("mail.smtp.user", from);
30 props.put("mail.smtp.password", pass);
31 props.put("mail.smtp.port", "465");
32 props.put("mail.smtp.auth", "true");
33 props.put("mail.smtp.ssl.enable", "true");
34 props.put("mail.smtp.ssl.trust", "smtp.mail.yahoo.com");
35
36
37 Session session = Session.getDefaultInstance(props);
38 session.setDebug(true);
39 MimeMessage message = new MimeMessage(session);
40
41 try {
42 message.setFrom(new InternetAddress(from));
43 InternetAddress[] toAddress = new InternetAddress[to.length];
44
45 // To get the array of addresses
46 for( int i = 0; i < to.length; i++ ) {
47 toAddress[i] = new InternetAddress(to[i]);
48 }
49
50 for( int i = 0; i < toAddress.length; i++) {
51 message.addRecipient(Message.RecipientType.TO, toAddress[i]);
52 }
53
54 message.setSubject(subject);
55 message.setText(body);
56 Transport transport = session.getTransport("smtp");
57 transport.connect(host, from, pass);
58 transport.sendMessage(message, message.getAllRecipients());
59 transport.close();
60 }
61 catch (Exception e) {
62 e.printStackTrace();
63 }
64 }
65}