New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
Getting startedUpdated 26 Oct 2026

Sending Mail From Servers and Scripts: Why Cron Jobs and PHP mail() Fail and What to Use Instead

Why mail sent by the local sendmail, PHP mail() or cron scripts often lands in spam or vanishes, how to move scripts to authenticated SMTP or an API, configuration examples, monitoring cron output and safe handling of secrets.

MO
Written by Mateus Oliveira
Senior SMTP and MTA Engineer
Reviewed by Kenji Watanabe
  • Published23 May 2025
  • Read time7 min
  • Length1,327 words
Share this guide

The oldest way to send email from a program is to hand the message to the local mail system: a cron job whose output is mailed to root, a PHP script calling mail(), a shell script piping text to sendmail. It still works on paper, and it is the cause of countless "my emails go to spam" and "my emails vanish" questions. The server that sends the message usually has no reverse DNS for mail, no SPF or DKIM, an IP address with a poor or unknown reputation, outbound port 25 blocked by the hosting provider, and no logs anyone reads. The message is often accepted by the local program and then silently deferred or rejected later. The fix is to give scripts a proper route: authenticated SMTP to a relay, or an HTTP email API, with a domain that is properly set up. This guide explains why the old way fails, how to diagnose it, how to configure common tools to use a relay, how to handle secrets, and how to monitor script mail. For related topics see sending from your app and which SMTP port to use.

ProblemLocal delivery from a server IP without authentication or reputation
SymptomsSpam folder placement, silent loss, port 25 timeouts, bounces to an unread mailbox
FixSend through authenticated submission (port 587 or 465) to a relay, or use an API
AlsoUse a proper From address on an authenticated domain and read the bounces

Why local sending fails

CauseEffectHow to check
Outbound port 25 blocked by the hosting or cloud providerConnection timeouts; mail stuck in the queue. See mail queue managementTest with telnet or openssl to a remote MX on port 25. See SMTP testing
Server IP has no reputation or is on a blocklistRejected or spam-folderedCheck with the blocklist check
No reverse DNS or a generic hostnameRejected by many receivers. See reverse DNSdig -x on the IP
No SPF or DKIM for the From domain, or SPF does not include the serverAuthentication fails; DMARC fails. See authenticate your domainRead Authentication-Results in a delivered message
From address on a domain you do not control (for example gmail.com)DMARC rejection or spam placementUse your own domain
Envelope sender is something like [email protected]Bounces go nowhere; SPF checks a meaningless domainSet the envelope sender explicitly
Shared hosting servers with many usersNeighbours' spam damages the IPAsk the host; prefer a relay
No bounce processingFailures unnoticedRead bounces. See bounce codes
Dynamic content from formsHeader injection abuse. See open relaysReview the script

The local program usually reports success because it only checked that it could accept the message into the queue. Success at that stage means nothing about delivery.

The better pattern

  1. Choose a relay or API with proper infrastructure and authentication. See what an SMTP relay is and email API vs SMTP relay.
  2. Verify and authenticate your domain with the relay: SPF include, DKIM keys, DMARC. See verify your sending domain.
  3. Create a credential per script or application, with the least privilege available.
  4. Connect on a submission port with TLS (587 with STARTTLS or 465 with implicit TLS) and authentication.
  5. Use a From address on your domain and a real Reply-To where replies matter.
  6. Process bounces and events via the provider's webhooks or logs.
  7. Send a test and read the headers to confirm SPF, DKIM and DMARC pass.

Configuration examples

A lightweight client for cron and shell scripts

A small SMTP client such as msmtp can replace the local sendmail binary so that every tool that calls sendmail or mail uses your relay:

# /etc/msmtprc
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        /var/log/msmtp.log

account        relay
host           smtp.example.net
port           587
tls_starttls   on
from           [email protected]
user           script-account
passwordeval   "cat /etc/msmtp.pass"

account default : relay

Set permissions on the credential file so only the service user can read it. Then point your cron mail to the client: set MAILTO in the crontab and make sure sendmail resolves to the client.

PHP

// php.ini: route mail() through the client above
sendmail_path = "/usr/bin/msmtp -t"

// Better: use a library with SMTP authentication (example with PHPMailer)
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
$mail->isSMTP();
$mail->Host       = 'smtp.example.net';
$mail->SMTPAuth   = true;
$mail->Username   = getenv('SMTP_USER');
$mail->Password   = getenv('SMTP_PASS');
$mail->SMTPSecure = 'tls';
$mail->Port       = 587;
$mail->setFrom('[email protected]', 'Example Alerts');

Python and shell

# Python standard library
import smtplib, ssl
from email.message import EmailMessage
msg = EmailMessage(); msg["From"]="[email protected]"; msg["To"]="[email protected]"
msg["Subject"]="Backup finished"; msg.set_content("Backup completed OK")
with smtplib.SMTP("smtp.example.net", 587) as s:
    s.starttls(context=ssl.create_default_context())
    s.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
    s.send_message(msg)

# Shell: send through the configured client
echo "Backup completed" | mail -s "Backup finished" [email protected]

For web applications, use the framework's mail configuration with the relay's settings; see for example Laravel mail configuration and Python smtplib.

Secrets and safety

  • Do not put passwords in scripts or crontabs. Read them from environment variables, a protected file or a secrets manager.
  • Do not commit credentials to version control. Rotate any that were. See rotating a key.
  • Use a separate credential for each script so you can revoke one without breaking others.
  • Restrict outbound access: allow the server to reach only the relay on the submission port, and block direct port 25 egress from application hosts. That also stops malware from spamming directly.
  • Validate any user input that influences headers or recipients. Never build the To or Bcc from raw form input without checks.
  • Apply rate limits in the script or the relay, so a bug cannot send thousands of messages. See SMTP security.

Cron mail and monitoring noise

Cron emails any output of a job to the owner or to MAILTO. It is easy to flood a mailbox or lose important alerts. Good habits: redirect routine output to a log and let the job print only on failure; use a clear subject line that names the job and the host; send alerts to a monitored shared address, not an individual; and use a monitoring service for critical jobs, which expects a ping and raises an alarm when it does not arrive, instead of relying on the absence of mail. Remember that "no email" can mean the job succeeded or that the mail system failed, so do not let silence be the only signal.

Containers and cloud hosts

Containers add a twist: they usually have no mail system at all, so a script that calls sendmail fails at once. Install a small client in the image, or better, make the application use an SMTP library or an HTTP API directly and pass the credentials through environment variables or the platform's secret store. Cloud providers often block outbound port 25 by default and may throttle mail on other ports for new accounts, so check their policies before launch. Avoid running a full mail server inside a container just to send alerts; it needs reverse DNS, reputation and maintenance that a relay already provides.

Troubleshooting checklist

  1. Does the script run and call the mail client? Add logging.
  2. Is the message in the local queue? Check the queue and the log of the client.
  3. Can the server reach the relay on the chosen port? Test with openssl.
  4. Do the credentials work? A 535 error means authentication failed. See 535 errors.
  5. Does the From domain pass SPF, DKIM and DMARC? Check the headers of a delivered message.
  6. Does the recipient reject or defer? Read the bounce or the provider log. See tracing messages.
  7. Is the message landing in spam? Check content and reputation. See why email is blocked.

Scripts deserve the same sending standards as products. A relay, an authenticated domain and a few lines of configuration turn unreliable, invisible mail into messages that arrive and that you can follow when they do not.

Give your scripts a proper route Authenticated SMTP and an API with logs and bounce handling.

Explore the SMTP relay

References and further reading

Frequently asked questions

Why does PHP mail() land in spam?

It sends from the web server with no authentication or reputation. Use authenticated SMTP or an API with a properly set up domain.

Why do my cron emails never arrive?

Outbound port 25 may be blocked, the sender is unauthenticated, or the mail is queued locally. Check the queue and logs.

What port should scripts use?

Port 587 with STARTTLS, or 465 with implicit TLS, with authentication to a relay.

How do I store the SMTP password safely?

In environment variables, a protected file or a secrets manager, not in the script or version control.

How do I know a script email was delivered?

Use the relay's logs and webhooks. A successful local send only means the message was queued.

Topics#cron#php mail#sendmail#scripts#smtp
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales