How do I send an SMTP Message from Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you send email from a Java app using Gmail?
How do I send an SMTP Message from Java?

Here's an example for Gmail smtp:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail#tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen#iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin#tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
http://commons.apache.org/email/
Regards
Tov Are Jacobsen

Another way is to use aspirin (https://github.com/masukomi/aspirin) like this:
MailQue.queMail(MimeMessage message)
..after having constructed your mimemessage as above.
Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.

Please see this post
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
It is specific to gmail but you can substitute your smtp credentials.

See the following tutorial at Java Practices.
http://www.javapractices.com/topic/TopicAction.do?Id=144

See the JavaMail API and associated javadocs.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}

Related

Sending EMail with Javamail via Exchange Server

we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535 5.7.8 Authentication credentials invalid

This piece of code is picked up from http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
//package com.tutorialspoint;
import java.util.Properties;
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 SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "ABC#gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR#gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I tried getting hint from this link. But it seems to be using a slightly different method.
On running it with a debugger, exception seems to be coming from following code:
Transport.send(message);
Following is the stack trace:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:58)
PS: I have checked the username and password. Also, 2 step sign in process is not enabled for the account from which I am trying to send mail.
Can someone please explain what could be the cause of authenticatio failure? Alternatively, if there is some other post which has already answered the query, please point me to it. Thanks.
The server isn't happy with the username or password you're using. You can probably guess the common reasons that might be the case, staring with you provided the wrong username or password.
The JavaMail Session debugging output might provide more information.
change String host = "relay.jangosmtp.net";
to String host = "smtp.gmail.com";
and Port from 25 to 587

Issue in sending email to a group email using java mail

As subject is self explanatory - I am facing issue in sending email to a group email using java mail.
I have gone through through several blogs & articles which are of no help & does not have a precise answer or hangs in middle.
Can you please help. Here is my mail class for you. My mail is going to have a link to ftp location & a text file as an attachment.
To separate the issue i tried to send a simple mail to the group as well but that didn't help either.
I tried to find answers in places like java-forums.org & Stack overflow but found no luck.
I appreciate your quality time & help in providing an insight to the issue.
To explain the issue better-
My Automation framework when completes the execution of test cases, it sends a mail to me with the link to execution report & a log file as an attachment. Now the audience for the report has expanded & we need to send the mail to a group email address.
When I set the email (to say group.email#company.com) none of the users in the group receives the mail. Where as if I send the email to my email address or anyone else email address it works.
I get no logs or error for this & so I am not able to understand the issue correctly.
An insight from the experts will help in understanding the issue.
Thanks in advance.
Akshat
import java.util.ArrayList;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class ReportMail {
private MimeMessage message = null;
private Session emailSession = null;
private MimeBodyPart textPart = null;
private ArrayList<MimeBodyPart> attachmentArray = null;
public void sendMailer(String mailToId, String string, String mailServer1,
int mailPort, String mailAdmin) {
Properties mailProperties = null;
mailProperties = new Properties();
String adminEmailId = mailAdmin;
String mailServer = mailServer1;
mailProperties.put("mail.transport.protocol", "smtp");
//mailProperties.put("mail.smtp.auth", "true");
mailProperties.put("mail.smtp.host", mailServer);
mailProperties.put("mail.from", adminEmailId);
mailProperties.put("mail.smtp.port", mailPort);
mailProperties.put("mail.to", mailToId);
try {
emailSession = Session.getInstance(mailProperties);
emailSession.setDebug(false);
message = new MimeMessage(emailSession);
textPart = new MimeBodyPart();
attachmentArray = new ArrayList<MimeBodyPart>(2);
message.addRecipients(RecipientType.TO, mailToId);
message.setSubject(string);
message.setFrom(new InternetAddress(adminEmailId));
setContent("PCM Automation Report");
//setContent("test123");
sendEMail();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setContent(String content) {
try {
textPart.setContent(content, "text/html");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean sendEMail() throws Exception {
try {
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
for (int i = 0; i < attachmentArray.size(); i++)
mp.addBodyPart(attachmentArray.get(i));
/********************
*
*/
// Part two is attachment
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Below is the link for the Test Automation report as link & attached Log file. PFA.");
//mp.addBodyPart(messageBodyPart);
String filename = "logfile.log"; //C:\workspacePCMSanity\PCMSanity\logfile.log
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
mp.addBodyPart(messageBodyPart);
/**
*
*/
message.setContent(mp);
Transport transport = emailSession.getTransport();
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return true;
}
}
In Microsoft Exchange Server there is a special group address setting option Require that all senders are authenticated. When an unknown user is used as a sender, such an email is rejected. You can either send emails in the name of real user or enable this option. In the latter case the group address is opened to spam.
http://technet.microsoft.com/en-us/library/bb124405%28v=exchg.141%29.aspx
Java doesn't know whether an email address is for a single user or a group.
Probably the issue with SMTP Server.

How to send mail in Java using same mechanism like in PHP mail()

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.
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:
Internet Mail Access Protocol (IMAP)
Simple Mail Transfer Protocol (SMTP)
Post Office Protocol 3 (POP 3)
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 = "abc#gmail.com";
String to = "xyz#gmail.com";
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();
}
}
}
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.
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
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.

How to send an email from a PC by a Java program?

What is required for sending mail from my computer by a Java program? I mean any changes, like enabling or disabling options, should be done from the PC.
Java has built in libraries for that.
import javax.mail.*;
import javax.mail.internet.*;
are the libraries you will need.
You need to have mail.jar in your classpath because it is not part of core Java.
You should have access to an SMTP server through which you mail can be sent. Also you will need to check that any firewall you have installed allows outgoing traffic on port 25 to communicate with the SMTP server.
Edit: if, as you mention below, you have no SMTP server access, you could sign up for a gmail account for your application and make use of the Gmail SMTP server (obviously not ideal for a business app, but perfectly fine as a personal app. For instruction on how to set this up, read this Lifehacker post.
The canonical way of creating and sending MIME-based email messages from Java (so it can contain HTML and images), is using JavaMail which is a very capable package, and which can even be taught to send mail through GMail over SSL if you do not have an internal SMTP-server available.
See http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ for two examples of how to do it.
Just change the email address and password. This example uses gmail. Also, you can have as many recipients as you wish.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class AnotherMail {
public static void main(String... args) {
String host = "smtp.gmail.com";
String from = "myEmail#gmail.com";
String pass = "MyPassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
String[] to = {"someRecipient#gmail.com"}; // added this line
try {
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) { // changed from a while loop
toAddress[i] = new InternetAddress(to[i]);
}
System.out.println(Message.RecipientType.TO);
for (int i = 0; i < toAddress.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mx) {
mx.printStackTrace();
}
}
}

Categories