-
Notifications
You must be signed in to change notification settings - Fork 3
/
SendMail.java
63 lines (52 loc) · 1.79 KB
/
SendMail.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.email;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail
{
public static void send(String to, String sub,
String msg, final String user,final String pass)
{
//create an instance of Properties Class
Properties props = new Properties();
/* Specifies the IP address of your default mail server
for e.g if you are using gmail server as an email sever
you will pass smtp.gmail.com as value of mail.smtp host.
As shown here in the code.
Change accordingly, if your email id is not a gmail id
*/
props.put("mail.smtp.host", "smtp.gmail.com");
//below mentioned mail.smtp.port is optional
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
/* Pass Properties object(props) and Authenticator object
for authentication to Session instance
*/
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user,pass);
}
});
try
{
/* Create an instance of MimeMessage,
it accept MIME types and headers
*/
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
/* Transport class is used to deliver the message to the recipients */
Transport.send(message);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}