I'm trying to send emails using Google Apps Migration API v.1, however I fail to send them and Code does not throw any exception or error.
Here is my code:
MailItemService mailItemService = new MailItemService("exampleCo-exampleApp-1");
mailItemService.setUserCredentials("user","password");
MailItemEntry entry = new MailItemEntry();
Rfc822MediaSource mediaSource = new Rfc822MediaSource(mail.getInputStream().toString());
entry.setMediaSource(mediaSource);
entry.addMailProperty(MailItemProperty.STARRED);
entry.addMailProperty(MailItemProperty.UNREAD);
entry.addLabel(new Label("pruebas"));
MailItemFeed feed = new MailItemFeed();
for (int i = 0; i < mailItems.size(); i++) {
BatchUtils.setBatchId(mailItems.get(i), Integer.toString(i));
feed.getEntries().add(mailItems.get(i));
}
mailItemService.batch("domain", "destinationUser", feed);
Can you define what you mean by "send"? It's against the APIs ToS to use it for anything other than migration of old mail to a mailbox (e.g. performing regular new message mailbox inserts is not allowed). If you're trying to send the mailbox new mail, use SMTP and/or IMAP.
Jay
Related
I want to make a call using VoiceResponse for all the info on how the call should work, but I can't seem to find how to generate a URI for the call to use (because it requires phone number, phone number, URI in the Call.creator method)
StringBuilder messageB = new StringBuilder();
for(int i = 2; i < input.split(" ").length; i++) {
messageB.append(" " + input.split(" ")[i]);
}
Say say = new Say.Builder(messageB.toString().replace(" ", "%20")).voice(Say.Voice.POLLY_JUSTIN).build();
Record recording = new Record.Builder().build();
Pause pause = new Pause.Builder().length(3).build();
TwiML response = new VoiceResponse.Builder().say(say).record(recording).pause(pause).build();
String Url = "http://twimlets.com/message";
Url = Url + "?Message%5B0%5D=" + messageB.toString();
Call call = Call.creator(
new PhoneNumber("+" + input.split(" ")[1]),
new PhoneNumber("+xxxxxxxxxxx"),
URI.create(Url))
.create();
System.out.println("Call ID: " + call.getSid());
System.out.println(Url);
Twilio developer evangelist here.
You can't use a VoiceResponse at the time you are making an API call to Twilio to start a call.
Instead, you need to set up a web application that can respond to incoming HTTP (webhook) requests from Twilio. When the call connects, Twilio will make a request to the URL you send as part of the request and you can use the VoiceResponse at that point to build and return the response you want.
You might find it useful to follow one of our tutorials to better understand this. Here's one on building a click to call system with Java.
Let me know if this helps at all.
My email code works well when I just send an email to a few people, but when I sending to all users(177) in contact, I got this error:
[ERROR] - org.apache.commons.mail.EmailException: Sending the email to the following server failed : hlrdwd.com:25
The code is below:
HtmlEmail email = new HtmlEmail();
email.setCharset("utf-8");
if (vo.getContent() != null && vo.getContent().trim().length() > 0) {
email.setHtmlMsg(vo.getContent());
} else {
email.setHtmlMsg(" ");
}
email.setSubject(vo.getTitle());
email.setFrom(vo.getSender(), currentuname);
email.setHostName(Property.getSmtp());
List<Map<String, String>> toList = mm.formatAddress(vo
.getReceiver());
if (toList != null) {
for (int i = 0; i < toList.size(); i++) {
Map<String, String> tMap = toList.get(i);
email.addTo(tMap.get(mm.KEY_EMAIL), tMap.get(mm.KEY_NAME));
System.out.println(tMap.get(mm.KEY_EMAIL));
}
}
email.setAuthentication(currentuser, password);
String messageid = email.send();
I google this and add email.setTLS(true);, but still can not work. Waiting your help!
The problem is that the receiving mail server doesn't like messages being sent to too many people at the same time. As a reference, postfix by default rejects messages with more than 50 recipients.
The simplest solution is to send multiple messages, rather than sending to everyone at once. In the extreme, you could send a message per user -- then you get the opportunity to customise the messages if you want, which also makes them less likely to be filtered as spam.
I am developing a java mail client using javamail api. I need to fetch the list of attachment without fetching it. First i will display the list of attachments and than on click of a particular attachment, i will fetch the data. Currently i am able to fetch the name of all attachments but it is taking too long time since i think my code is also fetching the attachment data. My code is as below
private void getAttachmentList(Part part, List list) throws Exception{
Object content = part.getContent();
if(content instanceof Multipart){
Multipart multiPart = (Multipart)content;
int no_of_part = multiPart.getCount();
for(int i=0; i<no_of_part; i++){
getAttachmentList(multiPart.getBodyPart(i), list);
}
}else{
String disposition = part.getDisposition();
if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
String fileName = part.getFileName();
if(fileName != null){
list.add(fileName);
}
}
}
}
I have tested this code with my gmail account and it is taking lots of time if my mail is having huge attachments. Any help is appreciated.
Thanks in advance
Do this app use POP, or IMAP?
If it uses POP, modify it to use IMAP. The latter may conceivably be quicker as it only downloads headers.
I would like to implement a 'Send Feedback' option in a Java desktop application. One which will pop up a box for the user to enter a comment, then send it to us along with a screenshot of the application window.
How would be the best way to communicate the data to us? Two obvious solutions spring to mind:
Email - I'm thinking that the application would connect to an SMTP server set-up by us, with the username/password somehow hidden in the code. SMTP over SSL for security (not of the data being sent, but of the SMTP username/password).
Web service - pretty self explanatory.
Which of these would be best, or is there a better alternative?
A webserivce would be far better, since the connection to an SMTP server might be blocked.
Another idea would be to use Google Docs. This would be like the website idea but you wouldnt need to set any server-side stuff yourself. You could create a Google Docs spreadsheet with the fields you will be collecting, then have your Java app write the submission to the spreadhseet using the google docs API. Then add a notification to the spreadsheet to automatically send you an email when a new row is written.
A web service sounds more reliable and less clumsy.
Client generally may make HTTP connections without firewall issues.
Much easier to setup, maintain and process HTTP server and requests.
As others mention, firewalls are an issue with SMTP. Still, there is a simple way to deliver mails without hosting your own infrastructure or "hidden" passwords. You could simply register a free mail account, e.g. gmail, and send mails directly to this address. As you aren't using Gmail's SMTP server as a relay, there is no need for username and password.
public static String[] lookupMailHosts(final String domainName) throws NamingException {
final InitialDirContext iDirC = new InitialDirContext();
final Attributes attributes = iDirC
.getAttributes("dns:/" + domainName, new String[] { "MX" });
final Attribute attributeMX = attributes.get("MX");
if (attributeMX == null) {
return new String[] { domainName };
}
final String[][] pvhn = new String[attributeMX.size()][2];
for (int i = 0; i < attributeMX.size(); i++) {
pvhn[i] = ("" + attributeMX.get(i)).split("\\s+");
}
// sort the MX RRs by RR value (lower is preferred)
Arrays.sort(pvhn, new Comparator<String[]>() {
public int compare(final String[] o1, final String[] o2) {
return Integer.parseInt(o1[0]) - Integer.parseInt(o2[0]);
}
});
// put sorted host names in an array, get rid of any trailing '.'
final String[] sortedHostNames = new String[pvhn.length];
for (int i = 0; i < pvhn.length; i++) {
sortedHostNames[i] = pvhn[i][1].endsWith(".") ? pvhn[i][1].substring(0, pvhn[i][1]
.length() - 1) : pvhn[i][1];
}
return sortedHostNames;
}
for example:
public static void main(String[] args) throws Exception {
// prints [gmail-smtp-in.l.google.com, alt1.gmail-smtp-in.l.google.com, alt2.gmail-smtp-in.l.google.com, alt3.gmail-smtp-in.l.google.com, alt4.gmail-smtp-in.l.google.com]
System.out.println(Arrays.asList(lookupMailHosts("gmail.com")));
}
so you would use "gmail-smtp-in.l.google.com" as your first choice for javax.mail:
Properties props = new Properties();
props.setProperty("mail.smtp.host", lookupMailHosts("gmail.com")[0]);
// ... other properies
Session smtpSession = Session.getInstance(props, null)
You could even combine this approach with a simple HTTP to SMTP kind of service hosted on AppEngine. All it would have to do is receive HTTP POST requests and forward them as an email using the method shown above.
I'd like to send mail without bothering with the SMTP-Server which is used for delivery.
So JavaMail API doesn't work for me because I have to specify a SMTP server to connect to.
I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.
I'm looking for something like Aspirin. Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.
An embeddable version of James would do the task. But I haven't found documentation concerning whether this is possible.
Or does anyone know about other libraries I could use?
One possible solution: get the MX record on your own and use JavaMail API.
You can get the MX record using the dnsjava project:
Maven2 dependency:
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.0.1</version>
</dependency>
Method for MX record retrieval:
public static String getMXRecordsForEmailAddress(String eMailAddress) {
String returnValue = null;
try {
String hostName = getHostNameFromEmailAddress(eMailAddress);
Record[] records = new Lookup(hostName, Type.MX).run();
if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }
if (log.isTraceEnabled()) {
// log found entries for debugging purposes
for (int i = 0; i < records.length; i++) {
MXRecord mx = (MXRecord) records[i];
String targetString = mx.getTarget().toString();
log.trace("MX-Record for '" + hostName + "':" + targetString);
}
}
// return first entry (not the best solution)
if (records.length > 0) {
MXRecord mx = (MXRecord) records[0];
returnValue = mx.getTarget().toString();
}
} catch (TextParseException e) {
throw new RuntimeException(e);
}
if (log.isTraceEnabled()) {
log.trace("Using: " + returnValue);
}
return returnValue;
}
private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
String parts[] = mailAddress.split("#");
if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
return parts[1];
}
Sending mail via JavaMail code:
public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
String smtpServer = getMXRecordsForEmailAddress(toAddress);
// create session
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props);
// create message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddress));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
msg.setSubject(subject);
msg.setText(body);
// send message
Transport.send(msg);
}
This is completely the wrong way to handle this.
Anyone connected to the internet will have some kind of "legit" SMTP server available to them to take the submission of email -- your ISP, your office, etc.
You WANT to leverage because they do several things for you.
1) they take your message and the responsibility to handle that message. After you drop it off, it's not your problem anymore.
2) Any mail de-spamming technologies are handled by the server. Even better, when/if those technologies change (Domain keys anyone?), the server handles it, not your code.
3) You, as a client of that sending mail system, already have whatever credentials you need to talk to that server. Main SMTP servers are locked down via authentication, IP range, etc.
4) You're not reinventing the wheel. Leverage the infrastructure you have. Are you writing an application or a mail server? Setting up mail server is an every day task that is typically simple to do. All of those casual "dumb" users on the internet have managed to get email set up.
Don't.
Sending email is much more complex than it seems. Email servers excel at (or should excel at) reliable delivery.
Set up a separate email server if you need to- that will be essentially the same as implementing one in Java (I doubt you will find libraries for this task- they would be essentially complete mail servers), but much more simpler.