Reputation: 3234
I'm having trouble in sending mail from my application. I can't use simple SMTP server on my application. And have no idea how to deal with sending mails in JAVA. I'm supposed to use same/similar mechanism like PHP's mail() uses. Unfortunately I have no idea how to do it.
Upvotes: 2
Views: 3805
Reputation: 310869
I'm supposed to use same/similar mechanism like PHP's mail() uses.
You can't, because it doesn't exist. If that's the requirement, get it changed.
Unfortunately I have no idea how to do it.
See the JavaMail API.
Upvotes: 0
Reputation: 18440
You can use JavaMail api with a local SMTP server like Apache James, so after installing and running James server, you can set the SMTP server ip to 127.0.0.1
Upvotes: 0
Reputation: 8247
The Java Mail API provides support for sending and receiving e-mails. The API provides a plug-in architecture where vendor’s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols:
Here is an example of how to use it:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public static void main(String[] args) {
String from = "[email protected]";
String to = "[email protected]";
String subject = "Test";
String message = "A test message";
SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Upvotes: 5
Reputation: 8543
You need to check out the JavaMail API, and as PHP's mail() requires, it will need an SMTP server to send that email.
If you require an SMTP server I suggest searching Google for an SMTP server for your operating system or maybe you could use an SMTP server provided by your ISP or server host.
Upvotes: 2