Send Email Using Java

How do I send an e-mail in Java?

Here's my code for doing that:

import javax.mail.*;
import javax.mail.internet.*;

// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);

// Construct the message
String to = "you@you.com";
String from = "me@me.com";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,\n\nHow are you?");

// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}

You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

I cannot send an Email using the Java Mail API the email is sent but is not received or displayed in the emails sent

This is class I use:

public class GMailSender extends javax.mail.Authenticator {

private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;

static {
Security.addProvider(new JSSEProvider());
}

public GMailSender(String user, String password, String host) {
this.user = user;
this.password = password;

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
if (host != null) mailhost = host;
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "587");

props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");

session = Session.getDefaultInstance(props, this);
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}

public synchronized void sendMail(String subject, String body, String sender, String recipients, String absolutePath, String fileName) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
//message.setContent(body, "text/plain");
// message.setDataHandler(handler);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp1);

if (absolutePath != null) {
MimeBodyPart mbp2 = new MimeBodyPart();

String file = absolutePath;
String name = "podpis";
if (fileName != null) name = fileName;
name += ".jpg";
DataSource source = new FileDataSource(file);
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName(name);
multipart.addBodyPart(mbp2);

}
message.setContent(multipart);

if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
Log.e("GMAIL SENDER", e.getMessage());
}
}

public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;

public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}

public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}

public void setType(String type) {
this.type = type;
}

public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}

public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}

public String getName() {
return "ByteArrayDataSource";
}

public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}

I'm attaching a file to it so you don't need two MimeBodyParts

That's the call:

String email = "email_adress_TO";

if (email != null && email.length() > 2 && email.contains("@")) {
final GMailSender sender = new GMailSender("your_email/name", "password", "hostname");
try {
sender.sendMail("Title",
"message",
"email_adress_FROM",
email,
null,
null);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}

Of course it's inside AsyncTask.

Sorry, I've totally forgotten about JSSEProvider. There you go:

import java.security.AccessController;
import java.security.Provider;

public class JSSEProvider extends Provider {

private static final long serialVersionUID = 1L;

public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}

how to send email from using outlook using a java api

package com.sendmail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendAttachmentInEmail {

private static final String SERVIDOR_SMTP = "smtp.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx@xxx.com"; //Cofig Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password

private final String from = "xxxx@xxx.com";
private final String to = "xxxx@xxx.com";

private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";

public void sendEmail() {
final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
}

});

try {
final Message message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.setText(messageContent);
message.setSentDate(new Date());
Transport.send(message);
} catch (final MessagingException ex) {
System.out.println(" "+ex);
}
}

public Properties getEmailProperties() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
return config;
}

public static void main(final String[] args) {
new SendAttachmentInEmail().sendEmail();
}

}

How to send email using javacode?

You have not given a password field in it. Additionally you have not specified your host. If you are sending email from local host, you should specify it. Also if you are sending mail by gmail server, you should use "smtp.gmail.com".
Check http://www.tutorialspoint.com/servlets/servlets-sending-email.htm for clarifying your problem. From this tutorial you can send email with attachment too. And if you need code in jsp, I can provide you.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Mail Program</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%@page import="java.sql.*"%>
<%@page import="javax.mail.*"%>

<%@page import="javax.mail.internet.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@ page import="java.math.BigInteger"%>

<%
String host = "smtp.gmail.com";
//host = smtp_server; //"smtp.gmail.com"; user = jsp_email; //"YourEmailId@gmail.com" // email id to send the emails
//pass = jsp_email_pw; //Your gmail password
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String to_add = request.getParameter("receiver");
String subject =request.getParameter("subject");
String messageText =request.getParameter("body");
String password = request.getParameter("pwd");
String from =request.getParameter("email_id");
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to_add) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setContent(messageText, "text/html"); // use setText if you want to send text
Transport transport = mailSession.getTransport("smtp");
System.setProperty("javax.net.ssl.trustStore", "conf/jssecacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "admin");
transport.connect(host, from, password);
try
{
transport.sendMessage(msg, msg.getAllRecipients());
out.println("sent");
//WasEmailSent = true; // assume it was sent
}
catch (Exception err)
{
//WasEmailSent = false; // assume it's a fail
out.println("Error" + err.getMessage());
}
transport.close();
%>
</body>
</html>

Implementing mailing properly in my java application

There were a few questions, so here are a few answers:

Try adding the following to your code -- they make things work better in Gmail:

properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.ssl.enable", "true");

and make sure your Authenticator is something like this:

javax.mail.Authenticator auth = new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
};

Google still has some sending limits. They are pretty high, but that's all subjective. If that doesn't work, here are a few more answers:

Java will allow you to send mail straight from your application. However, this will rarely if ever make it past email spam filters. So even though you can send it without the SMTP, it is not recommended. One of the main reasons these emails are blocked is because the ip address that sent the email isn't one of the valid MX records for that domain. SMTP makes it possible to send mail from a "trusted" source, and usually that means making it past spam filters.

With all that in mind, your other option, as you mentioned, is to make a local email server. However, that email server needs an MX Record for the "from" domain. Google provides a pretty comprehensive set of instructions for how to set that with the different DNS providers (all listed down the left side). i.e. if your from address is you@yourdomain.com, then yourdomain.com needs to have an MX Record pointing to the server that hosts your email server.

Hope that helps.



Related Topics



Leave a reply



Submit